jQuery(document).ready(function () {

	

/* GLOBALS */
recoda.loacalSaveUserPref = function(){
	li = document.querySelectorAll(".recoda-local-store-pull");
	recodaSetLocalStorage(li);
}
recoda.exportUserPref = function(){
	if (localStorage.getItem("recoda-settings") !== null)  {
		var localStore = window.localStorage.getItem('recoda-settings');
		var copyTextarea = document.querySelector('.rews-up-js-copytextarea');
		copyTextarea.value = localStore;
		copyTextarea.focus();
		copyTextarea.select();
	  
		try {
		  var successful = document.execCommand('copy');
		  var msg = successful ? 'successful' : 'unsuccessful';
		  console.log('Copying text command was ' + msg);
		} catch (err) {
		  console.log('Oops, unable to copy');
		}

	}
	else alert("There is no User prefs in Local Storage");
}
recoda.importUserPref = function(){
	setTimeout(function(){ 
		var t = document.querySelector(".rews-up-js-copytextarea").value;
		var pasteText = isJSON(t);
		if (pasteText == false) { 
			document.querySelector(".rews-up-js-copytextarea").value="NOTICE: NOT VALID INPUT";
			alert("Not valid JSON format, JSON test faild. Please check settings!");
			document.querySelector(".rews-up-js-copytextarea").value=""; 
			return;}
		else{
			var txt = JSON.parse(t);
			if (txt["recoda"] === "active"){
				console.log("Recoda Workspace: Successfully imported your User Preferences!");
				window.localStorage.setItem('recoda-settings', JSON.stringify(txt));
				recoda.showImportWizard();
				recoda.alert("Successfully imported your User Preferences!");

			}
			else { alert("Please imoport valid User Preferences!"); } 
		}
	
	}, 100);	
}
function isJSON(str) {
	try {
		return (JSON.parse(str) && !!str);
	} catch (e) {
		return false;
	}
}

//var b = document.getElementById("ct-controller-ui");
var b = document.querySelector("html");
var editor_theme = ['Respect API', 'Recoda Sleek', 'Recoda Designer', 'Recoda Developer','One Dark 3W','One Dark 2W', 'Dracula 3W', 'Dracula 2W', 'Classic Light', 'Classic Darker', 'Vodka Legacy',  'Custom']; 	
var code_fontSize = ['13','14','15', '16', '17', '18'];
var resize_handle_width = ['5','10','15', '20', '25'];
var structure_style = ['Classic','Sleek','Turn OFF']; 
var structure_ind = ['.5','.75','1','1.25' ]; 
var panel_docking = ['OFF','Left'];  
var def_ON_OFF = ['OFF','ON']; 
var panelator_position = ['Topbar','Sidepanel'];   
var magnetic_trigger = ['250','200','150', '100', '50'];

/* Set Prefs on Load */
recodaGetLocalStorage();


function recodaSelectOptions(o, option, label, def){
	var el= '';
	var options='';
	o.forEach((e) => { 
		var t;
		var b = e.toLowerCase().split(/[ ,]+/).join('-');
		t = `<option value="` + b +`">` + e + `</option>`;
		options = options + t;
		} )

	el = `<div class="recoda-option-row"><p class="recoda-option">`+label+`</p><select storekey="` + option +  `" class="recoda-local-store-pull">` + options + `</select></div>`;	
	return el;
}
function recodaRangeOptions(option, label, minVal, maxVal, step, currentVal){
	def_w = parseInt(getComputedStyle(document.documentElement).getPropertyValue(currentVal),10);
	var el= '';

		//    <input type="range" min="1" max="100" value="50" class="slider-square" id="id2">
	var input_template = `<input id="a" type="range" step="`+step+`" storekey="` + option +  `" class="recoda-local-store-pull"` + `min="`+minVal+`"`+ `max="`+maxVal+`"`+ `value="`+def_w+`"`+ `>`;
	el = `<div class="recoda-option-row pref-range"><p class="recoda-option">`+label+`</p><form onload="result.value=parseInt(a.value)" oninput="result.value=parseInt(a.value)"><output name="result" for="a" >`+def_w+`</output>` + input_template + `</form></div>`;	
	return el;
}
function recodaRangeDivideOptions(option, label, minVal, maxVal, step, currentVal){
	var def_w = parseInt(getComputedStyle(document.documentElement).getPropertyValue(currentVal),10);
	var def_val_r = 100 - def_w;
	var el= '';

		//    <input type="range" min="1" max="100" value="50" class="slider-square" id="id2">
	var input_template = `<input id="a" type="range" step="`+step+`" storekey="` + option +  `" class="recoda-local-store-pull"` + `min="`+minVal+`"`+ `max="`+maxVal+`"`+ `value="`+def_w+`"`+ `>`;
	el = `<div class="recoda-option-row pref-range-divider"><p class="recoda-option">`+label+`</p><form oninput="result1.value=parseInt(a.value); result2.value =100-parseInt(a.value) "><output name="result1" for="a">`+def_w+`</output>` + input_template + `<output name="result2" for="a">`+def_val_r+`</output></form> </div>`;	
	return el;
}
var rs1 = 					recodaSelectOptions(editor_theme, 		"ws-theme", 					"Theme:");
var rs2 = 					recodaSelectOptions(code_fontSize, 		"--code-font-size",			"Code Editor font-size:");
var rs3 = 					recodaSelectOptions(structure_style, 	"ws-dom",	"Structure Panel Style:");
var rs4 = 					recodaSelectOptions(resize_handle_width, 		"--resizer-handle-width",	 "Panel Resizer Handle Width:");
var rs5 =					recodaSelectOptions(panel_docking, 		"ws-docking",	 "Panel Docking:");
var rs6 =					recodaSelectOptions(def_ON_OFF, "ws-class-highlighter",	 "CL class highlighter:");
var rs7 =					recodaSelectOptions(panelator_position, "ws-panelator-position",	 "Panelator position:");
var rs8 =					recodaSelectOptions(structure_ind, "--ws-dom-indentation",	 "Structure indentation:");
var rs9 =					recodaSelectOptions(magnetic_trigger, "--magnetic-trigger",	 "Magnetic trigger width:");
var rs10 =					recodaSelectOptions(def_ON_OFF, "ws-hot-hint",	 "Shortcuts Guide:");
var rs11 =					recodaSelectOptions(def_ON_OFF, "ws-auto-zoom",	 "Auto Zoom:");
var rs12 =					recodaSelectOptions(def_ON_OFF, "ws-hide-sett-drop",	 "Hide Settings Dropdown:");
var rs13 =					recodaSelectOptions(def_ON_OFF, "ws-subtabs",	 "Classic Subtabs Style:");



var ri1 = recodaRangeOptions("--def-sidebar-width", "Left Panel Default Width", "250", "500","25", "--def-sidebar-width");
var ri2 = recodaRangeOptions("--def-sidepanel-width", "Right Panel Default Width", "250", "500","25", "--def-sidepanel-width");
var ri3 = recodaRangeOptions("--resizer-handle-width", "Panel Resizer Handle Width:", "5", "25","1", "--resizer-handle-width");

var rd1 = recodaRangeDivideOptions("--ratio", "Left/Right Panel Max. ratio:", "30", "70","1", "--ratio");

 recoda.showImportWizard = function(){
	var target = document.getElementById("rews-up-clip");
	var o = document.getElementById("recodaImportWizard");
	var copyTextarea = document.querySelector('.rews-up-js-copytextarea');
		
	if (!target.classList.contains("recoda-show-import-clip")){
		target.classList.add("recoda-show-import-clip");
		o.classList.add("active");
		copyTextarea.value = "";
		copyTextarea.focus();
		copyTextarea.select();
	} 
	else{
		target.classList.remove("recoda-show-import-clip");
		o.classList.remove("active");
	} 
}


jQuery(`<div class="rews-backdrop-modal-close ws-up ws-HIDE " onclick="recoda.openCloseModal('.rews-backdrop-modal-close.ws-up')"><div class="recoda-settings-container ws-popup"> <div class="ws-row" id="recodaUserPrefHeader"> <h3 class="ws-modal-title" >Recoda settings</h3><button class="ws-icon-btn ws-mL-auto" onclick="recoda.openCloseModal('.rews-backdrop-modal-close.ws-up')" ><svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"></path><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path></svg></button> </div> <div id="recodaSettingsContainer"></div> <div id="recodaUserPrefFooter"><button onclick="recoda.loacalSaveUserPref()">Save</button><button onclick="recoda.exportUserPref()">Export</button><button id="recodaImportWizard" onclick="recoda.showImportWizard()">Import</button><div class="rews-divider"></div><a href="https://feedback.recoda.me/" target="_blank">Feedback</a><a class="rews-disabled">Docs</a><a href="https://workspace.recoda.me/u/27c27215" target="_blank">Support</a><a class="rews-disabled">How to</a> <div id= "rews-up-clip" style="clip: rect(0,0,0,0);position: absolute;"><div class="recoda-import-wizdard-container"><p>Welcome to Import Wizard</p><p><span>STEP 1</span>Click on Textarea</p><p><span>STEP 2</span>Paste</p></div> <textarea placeholder="I'm textarea, Paste me here..&#10;Mac users: ⌘ + V  &#10;PC users: Ctrl + V " onpaste="recoda.importUserPref();" class="rews-up-js-copytextarea"></textarea></div>   </div></div> </div>`).prependTo("#oxygen-ui")


jQuery(		rs1 +ri1 +ri2 + rs4 + rd1 + rs2 + rs3 + rs5 + rs6 + rs7 + rs8 + rs9 + rs10 + rs11 + rs12 + rs13
			).prependTo("#recodaSettingsContainer")


/* SET ITEMS IN LS*/
let iVal = document.querySelectorAll(".recoda-local-store-pull");
iVal.forEach(function(elem) {
    elem.addEventListener('change', (event) => {
		recodaSetLocalStorage(iVal);
		recodaGetLocalStorage();
		//setRecodaUI();
	  });
});

function recodaLoadCurrentUserPref(list){
	var i = list;
	var b = JSON.parse(localStorage.getItem('recoda-settings'));
	i.forEach((item) => { 
		var key = item.getAttribute("storekey");
		for (var k in b) {
			if (b.hasOwnProperty(k)) {
				if(key == k){
					item.value = b[k];
				}
			}
		}
	})			
}
recodaLoadCurrentUserPref(iVal);


function recodaSetLocalStorage(list){
	var i = list;
	var recoda_settings = {
		recoda: 'active',
	};
	i.forEach((item) => { 
		var key = item.getAttribute("storekey");
		var keyValue = item.value;
		recoda_settings[key] = keyValue; 
		} )
		localStorage.setItem('recoda-settings', JSON.stringify(recoda_settings));
	}

		
	function recodaGetLocalStorage(){
		var localStore = JSON.parse(localStorage.getItem('recoda-settings'));
		var r = document.querySelector(':root');
		var d = document.querySelector("body");

		for (var key in localStore) {
			
			switch( key ) {
				case "ws-docking":
					var bodyClass = key+ "_" +localStore[key];
					var c = d.classList;
					for (i=0; i < c["length"]; i++){
						var s = c[i];
						if (s.includes(key)){
							d.classList.remove(s);
								}	
					}
					if(localStore[key] != "off") d.classList.add(bodyClass);
					recoda.dragElement( 
						document.getElementById("resizer-rp"),  
						"--sidepanel-width", 
						"--resizer-r-safe-area", 
						"right" );
					// 2) Left panel function call
					recoda.dragElement( 
						document.getElementById("resizer-lp"), 
						"--sidebar-width", 
						"--resizer-l-safe-area", 
						"left" );
				break;
				case "--ws-dom-indentation":
					r.style.setProperty(key, localStore[key] +'rem');
					r.style.setProperty("--ws-dom-indentation", localStore[key] +'rem');
				break;
				case "--magnetic-trigger":
					r.style.setProperty(key, localStore[key] +'px');
					r.style.setProperty("--magnetic-trigger", localStore[key] +'px');
				break;
				case "--def-sidebar-width":
					r.style.setProperty(key, localStore[key] +'px');
					r.style.setProperty("--sidebar-width", localStore[key] +'px');
				break;
				case "--def-sidepanel-width":
					r.style.setProperty(key, localStore[key] +'px');
					r.style.setProperty("--sidepanel-width", localStore[key] +'px');
				break;
				case "--code-font-size":
					r.style.setProperty(key, localStore[key] +'px');
					r.style.setProperty("--code-font-size", localStore[key] +'px');
				break;
				case "--resizer-handle-width":
					r.style.setProperty(key, localStore[key] +'px');
					r.style.setProperty("--resizer-handle-width", localStore[key] +'px');
				break;
				case "--ratio":
					r.style.setProperty(key, localStore[key] );
					r.style.setProperty("--ratio", localStore[key]);
				break;
				case "ws-theme": case "ws-dom":
					b.setAttribute(key, localStore[key])
				break;
				
				default:
					var bodyClass = key+ "_" +localStore[key];
					var c = d.classList;
					for (i=0; i < c["length"]; i++){
						var s = c[i];
						if (s.includes(key)){
							d.classList.remove(s);
								}	
					}
					if(localStore[key] != "off") d.classList.add(bodyClass);
					
			}
		}
	
	};
	
	
	/* UI MOVE THINGS AROUND */
	/*function setRecodaUI(){
		var localStore = JSON.parse(localStorage.getItem('recoda-settings'));
		if(localStore["ws-panelator-position"] == "sidepanel"){
			jQuery("#tbf-side-manager").prependTo("#oxygen-sidebar")
		}
	
	}
	setRecodaUI();
*/





});
