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

const store = {
  getItem: function (key) {
    return debug("GET", key, getStor().getItem(sha256(key + activeState.userId)));
  },
  setItem: function (key, data) {
    debug("SET", key, "setItem: "+data);
    getStor().setItem(sha256(key + activeState.userId), data);
  },
  removeItem: function (key) {
    getStor().removeItem(sha256(key + activeState.userId));
  },
  clear: function () {
    getStor().clear();
  },
};

const tempStore = {
  setItem: function (key, data) {
    globalThis.activeState.storage[key] = data;
  },
  getItem: function (key) {
    return globalThis.activeState.storage[key];
  },
  removeItem: function (key) {
    globalThis.activeState.storage[key] = "";
  },
  clear: function () {
    globalThis.activeState.storage = [];
  },
};

function getStor() {
  if (window.activeState.settings.persistentStorage == "true") {
    return window.localStorage;
  } else {
    return tempStore;
  }
}

function debug(mode, key, data) {
  if (activeState.settings.debug == "false") return data;
  console.log({
    mode: mode, 
    key: key,
    data: (data != null) ? data.substring(0,10): "", 
    persistent: activeState.settings.persistentStorage
  });
  return data;
}

function createStorageObj(ref = "none") {
  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);
  //set current filename according to filenamefield
  setCurrentFileName();

  //set savetime in templateFiles
  if (activeState.fileName != "") {
    let tF = retrieveData("templateFiles");
    if (tF.length != 0) {
      let c = 0;
      for (let tFi of tF) {
        if (tFi.fileName == activeState.fileName) {
          switch (ref) {
            case "save":
              tF[c].metadata.ts_save = getCurrentDate();
            break;
            case "copy":
              console.log("copy");
              tF[c].metadata.ts_copy = getCurrentDate();
            break;
          }
          storeData("templateFiles", tF);
        }
        c += 1;
      }
    }
  }
  storeData("userInput", dataArray);
}

function storeData(name, data) {
  if (passwordHash == "") return;
  data = JSON.stringify(data);
  //setCookie(name, btoa(data), 7);
  if (name == "userInput") {
    name = getFileName();
  }
  if (name == "userInputForce") {
    name = "userInput";
  }
  let lT = activeState.loadedTemplate;
  let key = name + "_m21_" + lT;
  if (name == "templateFiles") {
    key = name + "_m21_" + activeState.userId;
  }
  store.setItem(key, obfuscate(data));
}

function retrieveData(name, template = "none") {
  if (passwordHash == "") return null;
  if (name == "userInput") {
    if (activeState.fileName != "") {
      name = activeState.fileName;
    } else {
      return [];
    }
  }
  if (name == "userInputForce") {
    name = "userInput";
  }
  let cdata;
  let key;
  if (template == "none") {
    let lT = activeState.loadedTemplate;
    key = name + "_m21_" + lT;
    if (name == "templateFiles") {
      key = name + "_m21_" + activeState.userId;
    }
  } else {
    key = name + "_m21_" + template;
  }
  cdata = store.getItem(key);

  if (cdata != null) {
    cdata = obfuscate(cdata, false);
    let data;
    try {
      data = JSON.parse(cdata);
    } catch (e) {
      data = null;
    }
    return data;
  } else {
    return [];
  }
}

function clearData(name, template = "none") {
  let lT;
  let key;
  if (template == "none") {
    lT = activeState.loadedTemplate;
    key = name + "_m21_" + lT;
    if (name == "templateFiles") {
      key = name + "_m21_" + activeState.userId;
    }
  } else {
    lT = template;
    key = name + "_m21_" + template;
  }
  store.removeItem(key);
}

function getFileName() {
  let currentFileName = activeState.fileName;
  let lT = activeState.loadedTemplate;
  if (currentFileName == "none" || currentFileName == "") {
    let date = getCurrentDate();
    currentFileName = date.current_time + "_" + date.current_date + "  " + lT;
    //console.log(currentFileName);
  }

  let tF = retrieveData("templateFiles");
  const metadata = {
    ts_create: getCurrentDate(),
    ts_save: "",
    ts_copy: "",
    id: cyrb53(currentFileName),
  };

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

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

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

function createBookShelf() {
  let tF = retrieveData("templateFiles");
  let bookShelf = {};
  let date = getCurrentDate();
  let saveFileName = date.current_time + "_" + date.current_date;

  if (tF != null) {
    bookShelf[0] = { name: "hash", data: activeState.userId, ts: saveFileName };
    let i = 1;
    for (let tFi of tF) {
      let data = retrieveData(tFi.fileName, tFi.template);
      bookShelf[i] = {};
      bookShelf[i].name = tFi.fileName + "_m21_" + tFi.template;
      if (activeState.settings.localOnly == "true") {
        bookShelf[i].data = data;
      } else {
        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;
          store.setItem(file.name, file.data);
          templateFilesArray.push({
            fileName: file.name.split("_m21_")[0],
            template: file.name.split("_m21_")[1],
          });
        }
        store.setItem(
          "templateFiles_m21_" + activeState.userId,
          obfuscate(JSON.stringify(templateFilesArray))
        );
      }
    }
  };
  xhttp.open("GET", "php/?getStoredFiles=" + activeState.userId, true);
  xhttp.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded; charset=UTF-8"
  );
  xhttp.send();
}

function storeSettings(data, get = false) {
  let key = "settings_m21_" + activeState.userId;

  if (get) {
    let cdata = "";
    if (data == "getInit") {
      activeState.settings.persistentStorage = "true";
    }
    try {
      cdata = JSON.parse(obfuscate(store.getItem(key), false));
    } catch (e) {
      cdata = "";
    }
    if (data == "getInit") {
      activeState.settings.persistentStorage = "false";
    }
    return cdata;
  } else {
    store.setItem(key, obfuscate(JSON.stringify(data)));
  }
}

function clearStorage() {
  store.clear();
}

function setCurrentFileName() {
  activeState.fileName = "";
  let userFileNameField = document.getElementById("userFileName");
  let userFileName = sanitize(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;
  }
}

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