import XORCipher from "./xorc.js";
import sha256 from "./sha256.min.js";
import { getUsrId, passwordHash } from "./scripts.js";


function createStorageObj() {
  let x = document.getElementById("mainFormObj");
  let dataArray = [];
  if (x == null) {
    return;
  }
  for (let i = 0; i < x.length; i++) {
    dataArray.push({
      value: x.elements[i].value,
      name: x.elements[i].name,
    });
  }

  //console.log(this, dataArray);

  let userFileNameField = document.getElementById("userFileName");
  let userFileName = userFileNameField.value;
  let userFileNamePH = userFileNameField.getAttribute("placeholder");
  if (userFileName.length != 0) {
    activeState.fileName = userFileName;
    //clear old data as file switches to new filename
    if (userFileNamePH.length != 0) {
      clearData(userFileNamePH);
      popFromTemplateFiles(userFileNamePH);
    }
  } else if (userFileNamePH.length != 0) {
    activeState.fileName = userFileNamePH;
  } 

  storeData("userInput", JSON.stringify(dataArray));
  
}

function storeData(name, data) {
  //setCookie(name, btoa(data), 7);
  if (name == "userInput") {
    name = getFileName();
  }
  if (name == "userInputForce") {
    name = "userInput";
  }
  let lT = activeState.loadedTemplate;
  let key = sha256(name + "-" + lT);
  if (name == "templateFiles") {
    key = sha256(name + "-");
  }
  window.localStorage.setItem(key, obfuscate(data));
}

function retrieveData(type, template = "none") {
  if (type == "userInput") {
    let tF = JSON.parse(retrieveData("templateFiles"));
    if (tF == null) {
      return "";
    } else {
      type = tF[tF.length - 1].fileName;
    }
  }
  if (type == "userInputForce") {
    type = "userInput";
  }
  let cdata;
  if (template == "none") {
    let lT = activeState.loadedTemplate;
    let key = sha256(type + "-" + lT);
    if (type == "templateFiles") {
      key = sha256(type + "-");
    }
    cdata = window.localStorage.getItem(key);
  } else {
    let key = sha256(type + "-" + template);
    cdata = window.localStorage.getItem(key);
  }
  if (cdata != null) {
    return obfuscate(cdata, false);
  } else {
    return "[]";
  }
}

function clearData(type, template = "none") {
  let lT;
  let key;
  if (template == "none") {
    lT = activeState.loadedTemplate;
    key = sha256(type + "-" + lT);
    if (type == "templateFiles") {
      key = sha256(type + "-");
    }
  } else {
    lT = template;
    key = sha256(type + "-" + template);
  }
  window.localStorage.removeItem(key);
}

function getFileName() {
  let currentFileName = activeState.fileName;
  if (currentFileName == "none" || currentFileName == "") {
    let date = new Date();
    let current_hour = date.getHours();
    current_hour = current_hour <= 9 ? "0" + current_hour : current_hour;
    let current_minute = date.getMinutes();
    current_minute =
      current_minute <= 9 ? "0" + current_minute : current_minute;
    let current_month = date.getMonth() + 1;
    current_month = current_month <= 9 ? "0" + current_month : current_month;
    let current_year = date.getDate();
    current_year = current_year <= 9 ? "0" + current_year : current_year;

    let current_time = current_hour + ":" + current_minute;
    let current_date = current_year + "." + current_month;
    currentFileName = current_time + "_" + current_date;
    //console.log(currentFileName);
  }

  let lT = activeState.loadedTemplate;
  let tF = null;
  try {
    tF = JSON.parse(retrieveData("templateFiles"));
  } catch(e) {
    tF = null;
  }

  if (tF != null) {
    for (let tFi of tF) {
      if (tFi.fileName == currentFileName) {return currentFileName};
    }
    tF.push({ fileName: currentFileName, template: lT });
  } else {
    tF = [{ fileName: currentFileName, template: lT }];
  }
  storeData("templateFiles", JSON.stringify(tF));
  activeState.fileName = currentFileName;
  return currentFileName;
}

function obfuscate(data, mode = true) {
	if (mode) {
	  return XORCipher.encode(sha256(passwordHash), data);
	} else {
	  return XORCipher.decode(sha256(passwordHash), data);
	}
}

function popFromTemplateFiles(fileName) {
  let tF = JSON.parse(retrieveData("templateFiles"));
  let newArray = [];
  for (let obj of tF) {
    if (obj.fileName != fileName) {
      newArray.push(obj);
    }
  }
  storeData("templateFiles", JSON.stringify(newArray));
}

function createBookShelf() {
  let tF = JSON.parse(retrieveData("templateFiles"));
  let bookShelf = {};
  let date = new Date();
  let current_hour = date.getHours();
  current_hour = current_hour <= 9 ? "0" + current_hour : current_hour;
  let current_minute = date.getMinutes();
  current_minute =
    current_minute <= 9 ? "0" + current_minute : current_minute;
  let current_month = date.getMonth() + 1;
  current_month = current_month <= 9 ? "0" + current_month : current_month;
  let current_year = date.getDate();
  current_year = current_year <= 9 ? "0" + current_year : current_year;

  let current_time = current_hour + ":" + current_minute;
  let current_date = current_year + "." + current_month;
  let saveFileName = current_time + "_" + current_date;

  if (tF != null) {
    bookShelf[0] = {name: "hash", data: getUsrId(), ts: saveFileName};
    let i = 1;
    for (let tFi of tF) {
      let data = retrieveData(tFi.fileName, tFi.template);
      bookShelf[i] = {};
      bookShelf[i].name = tFi.fileName + "-" + tFi.template;
      bookShelf[i].data = obfuscate(data);
      i++;
    }
  }
  return bookShelf;
}

function importBookShelf() {

  localStorage.clear()
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      if (this.responseText == "none") {
        console.log("no files saved on server");
      } else {
        let respText = decodeURIComponent(this.responseText);
        let mainArray = JSON.parse(respText);
        let templateFilesArray = [];
        for (let file of mainArray) {
          if (file.name == "hash") continue;
          window.localStorage.setItem(sha256(file.name), file.data);
          templateFilesArray.push({ fileName: file.name.split("-")[0], template: file.name.split("-")[1] });
        }
        window.localStorage.setItem(sha256("templateFiles-"), obfuscate(JSON.stringify(templateFilesArray)));
      }
    }
  };
  xhttp.open("GET", "php/?getStoredFiles="+getUsrId(), true);
  xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhttp.send();
}

export { createStorageObj, storeData, retrieveData, clearData, getFileName, createBookShelf, importBookShelf};
