var m_globalLogins = new Map();
var m_Version = 0
var m_showPassword = false;
var m_showDialogPassword = false;
var m_editStr = "edit";
var m_showPasswordStr = "show password";
var m_deleteStr =  "delete";

//--------------------------------------------------------------
function doImport()
{
 window.CHtmlDialog.callLua( 'requestImport' );
}
//--------------------------------------------------------------
function doExport()
{
  window.CHtmlDialog.callLua( 'requestExport' );
}
//--------------------------------------------------------------
function getLogins()  
{ 
 let retA = []; 
  m_globalLogins.forEach(function (value, key, map) {
	  retA.push({'id': key,'name':value.name,'login':value.login,'password':value.password});
	});
 return retA;
}
//--------------------------------------------------------------
function clearLogins()  
{
 m_globalLogins.clear();
 let table = getLoginTable();
 if (table!=null)
     table.innerHTML = "";
}
//--------------------------------------------------------------
function getLoginTable()
{
 return document.getElementById("loginTable");
}
//--------------------------------------------------------------
function getRowById(id)
{
 let table = getLoginTable();
 if (table==null) return null;
 let r = table.rows;
 if (r==null) return null;
 return r.namedItem(id);
}
//--------------------------------------------------------------
function showRowPassword(id)  
{
 let item = m_globalLogins.get(id);
 if (undefined == item) return;
 let row = getRowById(id);
 if (row!=null)
    {
	  if (row.cells[3].textContent.startsWith('\u25CF'))
				row.cells[3].textContent = item.password;
	  else row.cells[3].textContent = item.password.replace(/(.)/g, '\u25CF');
	}
}
//--------------------------------------------------------------
function deleteEntry(id)  
{
 m_globalLogins.delete(id);
 let row = getRowById(id);
 if (row!=null)
	getLoginTable().deleteRow(row.rowIndex);
}
//-------------------------------------------------------------- 
function reloadLoginTable()
{
 let m = getLogins();
 clearLogins();
 m.forEach(function (item, index, array) {
	  addEntry(item.id,item.name,item.login,item.password);
	});
}
//-------------------------------------------------------------- 
function updateLoginRow(oldId,newId)
{
 let item = m_globalLogins.get(newId);
 if (undefined == item) return;
 
 if (oldId!=newId)
     {
	  let row = getRowById(newId);
	  if (row!=null)
	      getLoginTable().deleteRow(row.rowIndex);
	 }
	 
  let row = getRowById(oldId);
 if (row!=null)
  {
   row.innerHTML = ''
   fillRow(newId,row);
  } 
} 
//-------------------------------------------------------------- 
function addEntry(id,name,login,password) 
 {
  let table = getLoginTable();
  if (table==null) return;
  m_globalLogins.set(id,{'name' : name,'login' : login,'password' : password})
  
  let row = table.insertRow(-1);
  fillRow(id,row)
}
//-------------------------------------------------------------- 
function fillRow(id,row)
{  
  let item = m_globalLogins.get(id);
  if (undefined == item) return;
  
  row.id = id;
  let cellId = row.insertCell(0);
  let cellName = row.insertCell(1);
  let cellLogin = row.insertCell(2);
  let cellPassword = row.insertCell(3);
  let cellAction = row.insertCell(4);
  
  row.addEventListener("dblclick", function(){ editItem(id,false);}, false);
  
  cellId.textContent       = id;
  cellName.textContent     = item.name;
  cellLogin.textContent    = item.login;
  cellPassword.textContent = m_showPassword ? item.password : item.password.replace(/(.)/g, '\u25CF');
  
  cellAction.innerHTML   = "<img class='cell-button' src='Img/edit.png' title=\"" + m_editStr + "\" onclick=\"editItem('" + id + "',true);return false;\">"
+  (m_showPassword ? '' : "<img class='cell-button' src='Img/eye.png' title=\"" + m_showPasswordStr + "\" onclick=\"showRowPassword('" + id + "');return false;\">")
+ "<img class='cell-button' style=\"margin-left:16px;\" src='Img/btn_delete.png' title=\"" + m_deleteStr + "\" onclick=\"deleteEntry('" + id + "');return false;\">";  
  cellAction.style.userSelect = 'none';
  cellAction.addEventListener("dblclick", function(e){e.stopPropagation();}, false);

 } 
//--------------------------------------------------------------
function closeEditor()
{
 document.getElementById('editorForm').reset();
 document.getElementById('origLoginId').value = '';
 document.getElementById('editorAllArea').style.display = 'none';
}
//--------------------------------------------------------------
function isEditorOpen()
{
 return document.getElementById('editorAllArea').style.display != 'none';
}
//--------------------------------------------------------------
function onSubmitEditor()  
{
 let id     = document.getElementById('loginId').value.trim().toLowerCase();
 let origId = document.getElementById('origLoginId').value;
 let name = document.getElementById('loginName').value.trim();
 let login = document.getElementById('loginLogin').value.trim();
 let password = document.getElementById('loginPassword').value.trim();

 if ( 	 id==='' 
      || name==='')
   {
    //TODO: show error message
    return;
   }
 
 if (origId==='')  
    {
	 if (m_globalLogins.has(id))
		 origId = id;
	 else 
	  { 
	   addEntry(id,name,login,password) 
	   closeEditor();
	   return;
	  }
	}
  
 m_globalLogins.delete(origId);
 m_globalLogins.set(id,{'name' : name,'login' : login,'password' : password});
 updateLoginRow(origId,id);
 
 closeEditor();
}
//--------------------------------------------------------------
function newItem()  
{
 document.getElementById('editorContent').style.animationName = 'animatetop';
 document.getElementById('editorForm').reset();
 document.getElementById('origLoginId').value = '';
 document.getElementById('editorAllArea').style.display = 'block';
}
//--------------------------------------------------------------
function editItem(id,animDir)  
{
 let item = m_globalLogins.get(id);
 if (undefined == item) return;
 
 document.getElementById('editorForm').reset();
 
 document.getElementById('loginId').value = id;
 document.getElementById('origLoginId').value =  id;
 document.getElementById('loginName').value = item.name;
 document.getElementById('loginLogin').value = item.login;
 document.getElementById('loginPassword').value = item.password;
    
 document.getElementById('editorContent').style.animationName = animDir ? 'animateright' : 'animateopacity';
 document.getElementById('editorAllArea').style.display = 'block';
}
//--------------------------------------------------------------
function updateEditorShowPasswordButton()
{
 let b  = document.getElementById('editorShowPasswordButton');
 let ct = document.getElementById('loginPassword');
 if (m_showPassword)
      {
	   b.style.display = 'none';
	   ct.type = 'text';
	  }
  else {
        b.style.display = 'inline-block'; 
		ct.type = 'password';
	   }
}
//--------------------------------------------------------------
function editorShowPassword()
{
 let ct = document.getElementById('loginPassword');
 if (ct.type == 'password')
			ct.type = 'text';
 else  			
	ct.type = 'password';
}
//--------------------------------------------------------------
//Preference
//--------------------------------------------------------------
function openPreference()
{
 document.getElementById('prefShowPassCheckbox').checked = m_showPassword;
 document.getElementById('prefShowDialogPassCheckbox').checked = m_showDialogPassword;
 
 document.getElementById('prefAllArea').style.display = 'block';
}
//--------------------------------------------------------------
function isPreferenceOpen()
{
 return document.getElementById('prefAllArea').style.display != 'none';
}
//--------------------------------------------------------------
function closePreference()
{
 document.getElementById('prefAllArea').style.display = 'none';
}
//--------------------------------------------------------------
function onSubmitPref() 
{ 
 closePreference();
 
 m_showDialogPassword = document.getElementById('prefShowDialogPassCheckbox').checked;
 let v = document.getElementById('prefShowPassCheckbox').checked;
 if (v != m_showPassword)
    {
	 m_showPassword = v;
	 updateEditorShowPasswordButton();
	 reloadLoginTable();
	}
}
//--------------------------------------------------------------
//translate
//--------------------------------------------------------------
function tr(str)
{ 
 return new Promise(function(resolve, reject) 
  {
   window.CHtmlDialog.htmlTranslate(str,'simpleTV::PasswordManager'
        ,function(data)
        {
          resolve(data);
        });
  });  
}
//--------------------------------------------------------------
function doTranslate()  
{
 //Caption
 tr('Password Manager').then( data => document.getElementById('mainCaptionText').textContent = data + ' ' + m_Version);
 
 //Header table
 tr('Id').then( data => document.getElementById('headerId').textContent = data);
 tr('Name').then( data => document.getElementById('headerName').textContent  = data);
 tr('Login').then( data => document.getElementById('headerLogin').textContent  = data);
 tr('Password').then( data => document.getElementById('headerPass').textContent  = data);
 tr('Actions').then( data => document.getElementById('headerAct').textContent  = data);
  
 //Toolbar
 tr('New').then( data => document.getElementById('toollBarButtonNew').textContent  = data);
 tr('Import').then( data => document.getElementById('toollBarButtonImport').textContent  = data);
 tr('Export').then( data => document.getElementById('toollBarButtonExport').textContent  = data);
 tr('Preference').then( data => document.getElementById('toollBarButtonPref').textContent  = data);
  
 //Editor
 tr('Editor').then( data => document.getElementById('editorHeader').textContent  = data);
 tr('Id').then( data => document.getElementById('editorLabelId').textContent  = data);
 tr('Name').then( data => document.getElementById('editorLabelName').textContent  = data);
 tr('Login').then( data => document.getElementById('editorLabelLogin').textContent  = data);
 tr('Password').then( data => document.getElementById('editorLabelPass').textContent  = data);
 tr('Save').then( data => document.getElementById('editorSubmit').value = data);
 
 //Pref dialog
 tr('Preference').then( data => document.getElementById('prefHeader').textContent  = data);
 tr('Save').then( data => document.getElementById('prefSubmit').value = data);
  
 tr('Show passwords').then(data => {let v = document.getElementById('prefShowPassText');v.innerHTML = data + v.innerHTML;}); 
 tr('Show dialog of enter password').then(data => {let v = document.getElementById('prefShowDialogPassText');v.innerHTML =  data + v.innerHTML;});
}
//--------------------------------------------------------------
//not functions
//--------------------------------------------------------------
window.onclick = function(event) {
 if (event.target == document.getElementById('editorAllArea')) 
		{
		 closeEditor();  
		 return false;
		}
 if (event.target == document.getElementById('prefAllArea')) 
		{
		 closePreference();
		 return false;  		
		}
}
//--------------------------------------------------------------
window.onkeydown = function(event) {
 if (event.keyCode == 27) 
    {
	 if (isEditorOpen())
		{
 		 closeEditor();
		 return false;
		}
     if (isPreferenceOpen())
		{
 		 closePreference();
		 return false;
		}	
	}
 return true;	
}
//--------------------------------------------------------------
