'use strict';
class MiniFileExplorer{
	constructor( outDiv,fsRepresentation,editCB,refreshFsCB,refreshProjetCB,removeCB,execCB,startUpCB,changeNameCB,removeFolderCB,newFolderCB,newFileCB,newProjectCB){		
		self.outFSitemPaths = [];
		self.itemIDCounter = 0;
		self.getElementPath = function(id){
			var outPath = "";
			var res = self.outFSitemPaths[id];
			if (res[0] == -1){
				outPath = '/'+res[2];
			}else{
				while( true ){
					outPath = res[2]+'/'+outPath;
					res = self.outFSitemPaths[res[0]];
					if (res[0] == -1){
						outPath = res[2]+'/'+outPath;
						break;
					}
				}
				outPath = '/'+outPath.substr(0,outPath.length-1);
			}
			return outPath;
		}
		
		self.truncateItemName = function(strIn,truncateLen=20){			
			if (strIn.length > truncateLen){				
				return strIn.substr(0,truncateLen)+"~";				
			}else
				return strIn;			
		}
		
		self.browseElement = function(parentEl,inEl){
			var outEl = "";
			var currentDirectoryId = self.itemIDCounter;
			outEl += "<div id="+self.itemIDCounter+" data-isfolder=true onclick=\"self.lastElementFoccusID.push("+self.itemIDCounter+")\" class=\"FEC_folder\"><span>"+self.truncateItemName(inEl[0])+"</span>";
			outFSitemPaths.push([parentEl,self.itemIDCounter,inEl[0]]);
			self.itemIDCounter ++;
			outEl += "<ul class=\"FEC_nested treeindentation\">";
			if ( inEl.length > 1 )
				for (var i = 1 ; i < inEl.length  ; i++)
					if (typeof inEl[i] == "string"){
						outEl += "<div id="+self.itemIDCounter+" data-isfolder=false onclick=\"self.lastElementFoccusID.push("+self.itemIDCounter+")\" class=\"FEC_pyFile\">"+self.truncateItemName(inEl[i])+"</div>";
						outFSitemPaths.push([currentDirectoryId,self.itemIDCounter,inEl[i]]);
						self.itemIDCounter ++;
					}
					else
						outEl += self.browseElement(currentDirectoryId,inEl[i]);	
				outEl += "</ul></div>"
			return outEl;
		}
		self.togglerDirectory = document.getElementsByClassName("FEC_folder");
		self.togglerFile = document.getElementsByClassName("FEC_pyFile");
		self.currentSelectedMenuItem = [-1,0,0];
		self.itemClickListener = function(){
			
			event.stopPropagation();
			
			this.classList.toggle("FEC_iem-selected",true);
			for (var j = 0; j < self.togglerDirectory.length; j++)
				if ( this.id != self.togglerDirectory[j].id )
					self.togglerDirectory[j].classList.toggle("FEC_iem-selected",false);
			for (var j = 0; j < self.togglerFile.length; j++)
				if ( this.id != self.togglerFile[j].id )
					self.togglerFile[j].classList.toggle("FEC_iem-selected",false);
				
			if (this.dataset.isfolder == 'true'){
				this.childNodes[1].parentElement.querySelector(".FEC_nested").classList.toggle("active_subelement");

			}
			if (self.currentSelectedMenuItem[0] != -1 && self.currentSelectedMenuItem[0] != this.id){
				
				for (var j = 0; j < self.togglerDirectory.length; j++)
					if ( self.togglerDirectory[j].id == self.currentSelectedMenuItem[0] ){
						self.togglerDirectory[j].removeChild(self.currentSelectedMenuItem[1]);
						self.currentSelectedMenuItem[0] = -1;
						break;
					}
				if (self.currentSelectedMenuItem[0] != -1){
					for (var j = 0; j < self.togglerFile.length; j++)
						if ( self.togglerFile[j].id == self.currentSelectedMenuItem[0] ){
							self.togglerFile[j].removeChild(self.currentSelectedMenuItem[1]);
							break;
						}
				}				
			}
			
			
			if(self.currentSelectedMenuItem[0] != this.id){			
				self.currentSelectedMenuItem[0] = this.id;
				console.warn(self.currentSelectedMenuItem[0]);				
				var node=document.createElement("div");
				node.id = "itemToolBoxActive";
				node.className = "FEC_fileItemToolBox";	
				self.currentSelectedMenuItem[1] = node;
				this.appendChild(node);					
				if (this.dataset.isfolder == 'true'){
					if(this.childNodes[0].innerHTML == "Projet"){
						node.innerHTML = 
						"<div id='FEC-ActiveMkdirBtnProjet' class=\"FEC_itemTollBox\">&#43;&#128448;"+
							"<span class=\"FEC_tooltip\">Créer un nouveau projet</span>"+
						"</div>"+
						"<div id='FEC-ActiveRemoveBtnFolder' class=\"FEC_itemTollBox\">&#x274C;"+
							"<span class=\"FEC_tooltip\">Remove the folder and it entire content.</span>"+
						"</div>";
						document.getElementById("FEC-ActiveMkdirBtnProjet").addEventListener("click",function(){
						event.stopPropagation();
						var node=document.createElement("div");
						node.id='itemToolBoxActive'
						node.className = "FEC_fileItemToolBox";	
						node.innerHTML = 
							"<div onclick='event.stopPropagation();'> Nouveau Projet :</div>"+
							"<input id=\"FEC_mkdirnameInput\" class=\"FEC_itemTollBox\" style='color:white;width:80%;' onclick='event.stopPropagation();this.focus();' type='text'/>"+
							"<div id=\"FEC_mkdirnameInputActiveBtn\" class=\"FEC_itemTollBox\" style=\"color:#1dfe30\">&#x2714;</div>";						
						this.parentNode.parentNode.appendChild(node);						
						self.currentSelectedMenuItem[1].parentElement.querySelector(".FEC_nested").classList.toggle("FEC_active",false);
						self.currentSelectedMenuItem[1].parentNode.removeChild(self.currentSelectedMenuItem[1]);
						self.currentSelectedMenuItem[1] = node;
						node.childNodes[2].addEventListener("click",function(){
							event.stopPropagation();
							var typedName = document.getElementById("FEC_mkdirnameInput").value;
							var validFilename = !/[^a-z0-9_() -]/i.test(typedName);
							if ( validFilename && typedName.length > 0 ){	
								newProjectCB(typedName).then(_ =>{		
									refreshFsCB();
									refreshProjetCB();
								});
							}else{
								alert("Invalid folder name...");
								document.getElementById("FEC_mkdirnameInput").value = "";								
							}
						});
						document.getElementById("FEC_mkdirnameInput").addEventListener("keydown",function(event){
							if (event.keyCode === 13)
								document.getElementById("FEC_mkdirnameInputActiveBtn").click();
						});
					});
					
					
					}else{
						node.innerHTML = 
						"<div id='FEC-ActiveMkFilBtnFolder' class=\"FEC_itemTollBox\">&#43;&#128459;"+
							"<span class=\"FEC_tooltip\">Create a file</span>"+
						"</div>"+
						"<div id='FEC-ActiveMkdirBtnFolder' class=\"FEC_itemTollBox\">&#43;&#128448;"+
							"<span class=\"FEC_tooltip\">Create a sub-folder</span>"+
						"</div>"+
						"<div id='FEC-ActiveRemoveBtnFolder' class=\"FEC_itemTollBox\">&#x274C;"+
							"<span class=\"FEC_tooltip\">Remove the folder and it entire content.</span>"+
						"</div>";
					
						document.getElementById("FEC-ActiveMkdirBtnFolder").addEventListener("click",function(){
							event.stopPropagation();
							var node=document.createElement("div");
							node.id='itemToolBoxActive'
							node.className = "FEC_fileItemToolBox";	
							node.innerHTML = 
								"<div onclick='event.stopPropagation();'>Nouveau dossier :</div>"+
								"<input id=\"FEC_mkdirnameInput\" class=\"FEC_itemTollBox\" style='color:white;width:80%;' onclick='event.stopPropagation();this.focus();' type='text'/>"+
								"<div id=\"FEC_mkdirnameInputActiveBtn\" class=\"FEC_itemTollBox\" style=\"color:#1dfe30\">&#x2714;</div>";						
							this.parentNode.parentNode.appendChild(node);						
							self.currentSelectedMenuItem[1].parentElement.querySelector(".FEC_nested").classList.toggle("FEC_active",false);
							self.currentSelectedMenuItem[1].parentNode.removeChild(self.currentSelectedMenuItem[1]);
							self.currentSelectedMenuItem[1] = node;
							node.childNodes[2].addEventListener("click",function(){
								event.stopPropagation();
								var typedName = document.getElementById("FEC_mkdirnameInput").value;
								var validFilename = !/[^a-z0-9_() -]/i.test(typedName);
								if ( validFilename && typedName.length > 0 ){
									newFolderCB(getElementPath(currentSelectedMenuItem[0])+'/'+typedName);
									refreshFsCB();
									refreshProjetCB();
								}else{
									alert("Invalid folder name...");
									document.getElementById("FEC_mkdirnameInput").value = "";								
								}
							});
							document.getElementById("FEC_mkdirnameInput").addEventListener("keydown",function(event){
								if (event.keyCode === 13)
									document.getElementById("FEC_mkdirnameInputActiveBtn").click();
							});
						});	
						document.getElementById("FEC-ActiveMkFilBtnFolder").addEventListener("click",function(){
							event.stopPropagation();
							var node=document.createElement("div");
							node.id='itemToolBoxActive'
							node.className = "FEC_fileItemToolBox";	
							node.innerHTML = 
								"<div onclick='event.stopPropagation();'>Nouveau Fichier :</div>"+
								"<input id=\"FEC_mkdirnameInput\" class=\"FEC_itemTollBox\" style='color:white;width:80%;' onclick='event.stopPropagation();this.focus();' type='text'/>"+
								"<div id=\"FEC_mkdirnameInputActiveBtn\" class=\"FEC_itemTollBox\" style=\"color:#1dfe30\">&#x2714;</div>"/*+*/
								/*"<div class=\"FEC_itemTollBox\" style=\"color:#fd0202\">&#128473;</div>"*/;	
							this.parentNode.parentNode.appendChild(node);						
							self.currentSelectedMenuItem[1].parentElement.querySelector(".FEC_nested").classList.toggle("FEC_active",false);
							self.currentSelectedMenuItem[1].parentNode.removeChild(self.currentSelectedMenuItem[1]);
							self.currentSelectedMenuItem[1] = node;
							node.childNodes[2].addEventListener("click",function(){
								event.stopPropagation();
								var typedName = document.getElementById("FEC_mkdirnameInput").value;
								var count = (typedName.match(/\./g) || []).length;
								var validFilename = ( (!/[^a-z0-9_(). -]/i.test(typedName)) && ( count == 1 ) );
								if (validFilename && typedName.length > 0){
									newFileCB(getElementPath(currentSelectedMenuItem[0])+'/'+typedName, _ =>{
										refreshFsCB();
									});
									
								}else{
									alert("Invalid file name...");
									document.getElementById("FEC_mkdirnameInput").value = "";								
								}
							});
							document.getElementById("FEC_mkdirnameInput").addEventListener("keydown",function(event){
								if (event.keyCode === 13)
									document.getElementById("FEC_mkdirnameInputActiveBtn").click();
							});
						});								
					
					
					}
					// console.log(this.childNodes[0].innerHTML);
					document.getElementById("FEC-ActiveRemoveBtnFolder").addEventListener("click",function(){
						event.stopPropagation();
						document.getElementById("itemToolBoxActive").innerHTML = 
							"Confirm deletion ?"+
							"<div id='FEC-ItemRemoveConfirmDeletion' class=\"FEC_itemTollBox\" style=\"color:#fd0202\">&#x2714;</div>"+
							"<div class=\"FEC_itemTollBox\" style=\"color:#1dfe30\">&#128473;</div>";
						document.getElementById("FEC-ItemRemoveConfirmDeletion").addEventListener("click",function(){
							removeFolderCB(getElementPath(currentSelectedMenuItem[0]));
							event.stopPropagation();
							document.getElementById(currentSelectedMenuItem[0]).parentNode.removeChild(document.getElementById(currentSelectedMenuItem[0]));
						});						
					});	
					
			
				}else{
					node.innerHTML = "";
					var filePath = getElementPath(currentSelectedMenuItem[0]);
					var extention = filePath.substr(filePath.lastIndexOf('.'),filePath.length);
					if (extention == ".txt" || extention == ".htm" || extention == ".html" || extention == ".py" || extention == ".js" || extention == ".inf" || extention == ".blk" || extention == ".log")
						node.innerHTML += 
							"<div id='FEC-ActiveOpenEditorBtn' class=\"FEC_itemTollBox\" style=\"color:#ffe100\">&#x1F4DD;"+
							"<span class=\"FEC_tooltip\">Open in the editor.</span>"+
							"</div>";
					if( extention == ".py" )						
						node.innerHTML += 
							"<div id='FEC-ActiveExecBtn' class=\"FEC_itemTollBox\" style=\"color:#07ff34\">&#x2BC8;"+
								"<span class=\"FEC_tooltip\">Execute immediately.</span>"+
							"</div>"+						
							"<div id='FEC-ActiveStartUpBtn' class=\"FEC_itemTollBox\" style=\"color:#0fa3f6\">&#x1F3C1;"+
								"<span class=\"FEC_tooltip\">Set as default startup file.</span>"+
							"</div>";										
					node.innerHTML +=					
					"<div id='FEC-ActiveRenameBtn' class=\"FEC_itemTollBox\" style=\"color:white\">&#9999;&#128631;"+
						"<span class=\"FEC_tooltip\">Change filename.</span>"+
					"</div>"+	
					"<div id='FEC-ActiveRemoveBtn' class=\"FEC_itemTollBox\">&#x274C;"+
						"<span class=\"FEC_tooltip\">Remove the file.</span>"+
					"</div>";
					document.getElementById("FEC-ActiveRemoveBtn").addEventListener("click",function(){
						event.stopPropagation();
						document.getElementById("itemToolBoxActive").innerHTML = 
							"Confirm deletion ?"+
							"<div id='FEC-ItemRemoveConfirmDeletion' class=\"FEC_itemTollBox\" style=\"color:#fd0202\">&#x2714;</div>"+
							"<div class=\"FEC_itemTollBox\" style=\"color:#1dfe30\">&#128473;</div>";
						document.getElementById("FEC-ItemRemoveConfirmDeletion").addEventListener("click",function(){
							removeCB(getElementPath(currentSelectedMenuItem[0]));
							event.stopPropagation();
							document.getElementById(currentSelectedMenuItem[0]).parentNode.removeChild(document.getElementById(currentSelectedMenuItem[0]));
						});						
					});	
					if (document.getElementById("FEC-ActiveExecBtn") != null)		
						document.getElementById("FEC-ActiveExecBtn").addEventListener("click",function(){
							event.stopPropagation();
							execCB(getElementPath(currentSelectedMenuItem[0]));						
						});
					if (document.getElementById("FEC-ActiveStartUpBtn") != null)	
						document.getElementById("FEC-ActiveStartUpBtn").addEventListener("click",function(){
							event.stopPropagation();	
							startUpCB(getElementPath(currentSelectedMenuItem[0]));						
						});
					if (document.getElementById("FEC-ActiveOpenEditorBtn") != null)
						document.getElementById("FEC-ActiveOpenEditorBtn").addEventListener("click",function(){
							event.stopPropagation();	
							editCB(getElementPath(currentSelectedMenuItem[0]));						
						});		
					document.getElementById("FEC-ActiveRenameBtn").addEventListener("click",function(){
						event.stopPropagation();
						var node=document.createElement("div");
						node.id='itemToolBoxActive'
						node.className = "FEC_fileItemToolBox";	
						node.innerHTML = 
							"<div onclick='event.stopPropagation();'>New file, name :</div>"+
							"<input id=FEC_mkdirnameInput class=\"FEC_itemTollBox\" style='color:white;width:80%;' onclick='event.stopPropagation();this.focus();' type='text'/>"+
							"<div id=\"FEC_mkdirnameInputActiveBtn\" class=\"FEC_itemTollBox\" style=\"color:#1dfe30\">&#x2714;</div>"/*+*/
							/*"<div class=\"FEC_itemTollBox\" style=\"color:#fd0202\">&#128473;</div>"*/;
						this.parentNode.parentNode.appendChild(node);						
						self.currentSelectedMenuItem[1].parentNode.removeChild(self.currentSelectedMenuItem[1]);
						self.currentSelectedMenuItem[1] = node;
						node.childNodes[2].addEventListener("click",function(){
							event.stopPropagation();
							var typedName = document.getElementById("FEC_mkdirnameInput").value;
							var count = (typedName.match(/\./g) || []).length;
							var validFilename = ( (!/[^a-z0-9_(). -]/i.test(typedName)) && ( count == 1 ) );
							if (validFilename && typedName.length > 0){
								changeNameCB(getElementPath(currentSelectedMenuItem[0]),typedName);
								refreshFsCB();
								refreshProjetCB();
							}else{
								alert("Invalid filename...");
								document.getElementById("FEC_mkdirnameInput").value = "";								
							}
						});
						document.getElementById("FEC_mkdirnameInput").addEventListener("keydown",function(event){
							if (event.keyCode === 13)
								document.getElementById("FEC_mkdirnameInputActiveBtn").click();
						});
					});	
				}							
			}		
		}
		self.loadFileExplorerContent = function(self,treeRepresentation){
			itemIDCounter = 0;			
			var fsRepresentationOut = "";
			if ( treeRepresentation.length > 0 ){				
				treeRepresentation.forEach(function(el){
					
					if (typeof el == "string"){
						fsRepresentationOut += "<div id="+itemIDCounter+" data-isfolder=false onclick=\"self.lastElementFoccusID.push("+itemIDCounter+")\" class=\"FEC_pyFile\">"+truncateItemName(el)+"</div>";
						outFSitemPaths.push([-1,itemIDCounter,el]);
						itemIDCounter ++;
					}
					else fsRepresentationOut += browseElement(-1,el);	
				});
				document.getElementById("FileExplorerContainer").innerHTML=fsRepresentationOut;				
				for (var i = 0; i < togglerDirectory.length; i++){
					togglerDirectory[i].addEventListener('mousedown', function(e){ e.preventDefault(); }, true);
					togglerDirectory[i].addEventListener("click",itemClickListener);
				}				
				for (var i = 0; i < togglerFile.length; i++){
					togglerFile[i].addEventListener('mousedown', function(e){ e.preventDefault(); }, false);
					togglerFile[i].addEventListener("click",itemClickListener);
				}
			}else
				document.getElementById("FileExplorerContainer").innerHTML="<div><span class=\"FEC_noFile\"/></div>";
		}	
		self.loadFileExplorerContent(this,fsRepresentation);
		self.loadProjetExplorerContent = function(self,treeRepresentation){
			itemIDCounter = 0;			
			var fsRepresentationOut = "";
			if ( treeRepresentation.length > 0 ){	
				console.warn(treeRepresentation);			
				treeRepresentation.forEach(function(el){
					
					if (typeof el == "string"){
						fsRepresentationOut += "<div id="+itemIDCounter+" data-isfolder=false onclick=\"self.lastElementFoccusID.push("+itemIDCounter+")\" class=\"FEC_pyFile\">"+truncateItemName(el)+"</div>";
						outFSitemPaths.push([-1,itemIDCounter,el]);
						itemIDCounter ++;
					}
					else fsRepresentationOut += browseElement(-1,el);	
				});
				document.getElementById("NavigationProjet").innerHTML=fsRepresentationOut;				
				for (var i = 0; i < togglerDirectory.length; i++){
					togglerDirectory[i].addEventListener('mousedown', function(e){ e.preventDefault(); }, true);
					togglerDirectory[i].addEventListener("click",itemClickListener);
				}				
				for (var i = 0; i < togglerFile.length; i++){
					togglerFile[i].addEventListener('mousedown', function(e){ e.preventDefault(); }, false);
					togglerFile[i].addEventListener("click",itemClickListener);
				}
			}else
				document.getElementById("NavigationProjet").innerHTML="<div><span class=\"FEC_noFile\"/></div>";
		}
		self.loadProjetExplorerContent(this,fsRepresentation);		
		this.reloadFsContent = function(treeRepresentation){
			self.outFSitemPaths = [];
			self.itemIDCounter = 0;			
			self.currentSelectedMenuItem = [-1,0,0];
			self.loadFileExplorerContent(this,treeRepresentation);
			self.togglerDirectory = document.getElementsByClassName("FEC_folder");
			self.togglerFile = document.getElementsByClassName("FEC_pyFile");
			self.tryRestaureLastElementFoccus();
		}
		this.reloadProjetContent = function(treeRepresentation){
			self.outFSitemPaths = [];
			self.itemIDCounter = 0;			
			self.currentSelectedMenuItem = [-1,0,0];
			self.loadProjetExplorerContent(this,treeRepresentation);
			self.togglerDirectory = document.getElementsByClassName("FEC_folder");
			self.togglerFile = document.getElementsByClassName("FEC_pyFile");
			self.tryRestaureLastElementFoccus();
		}
		// document.getElementById("refreshFSTress").addEventListener("click",function(){
		// 	refreshFsCB();		
		// });
		// document.getElementById("refreshProjetTress").addEventListener("click",function(){
		// 	refreshProjetCB();		
		// });
		// document.getElementById("coding").addEventListener("click",function(){
			// refreshFsCB();						
		// });
		// document.getElementById("moovetocreat").addEventListener("click",function(){
		// 	refreshFsCB();						
		// });	
		
		self.lastElementFoccusID = [];
		// Must be optimized !
		self.tryRestaureLastElementFoccus = function(){
			var tmplastElementFoccusID = [];
			self.lastElementFoccusID.forEach(function(id){
				tmplastElementFoccusID.push(id);
			});			
			tmplastElementFoccusID.forEach(function(id){
				document.getElementById(id).click();	
			});
			self.lastElementFoccusID = tmplastElementFoccusID;	
		}
	}
}