console.log("Hello world!");

var getAllMessagesURL = `http://${hostAddress}/api/admin/get/messages/`; //hostAddress set in thymeleaf backend
var reencryptURL = `http://${hostAddress}/api/admin/post/re-encrypt`;
var getAllRegularUsersURL = `http://${hostAddress}/api/regular-users`;
var username = sessionStorage.getItem("username");
var password = sessionStorage.getItem("password");
var authToken = "Basic " + btoa(username + ":" + password);
var iterations = 10000;

function handleAddToAdminForm() {
  document
    .getElementById("addUserToAdminForm")
    .addEventListener("submit", function (e) {
      e.preventDefault();
      getAllRegularUsers();
      // .then(usernamesArray => {
      //     console.lo
      // });
    });
}

function handleChangePassphraseForm() {
  document
    .getElementById("changePassphraseForm")
    .addEventListener("submit", function (e) {
      e.preventDefault();
      let changePassphraseDropDown = document.getElementById(
        "changePassphraseDropDown"
      );
      let user = changePassphraseDropDown.value;
      let passphraseOld = document.getElementById("passphraseOld");
      let passphraseNew = document.getElementById("passphraseNew");
      // let messageCipherNew = {};
      console.log(user);
      getAllMessages(user)
        .then((json) => {
          console.log(json);

          return json;
        })
        .then((json) => {
          let jsonNew = [];
          let messageCiphers = [];
          let chatMessageDTOs = [];
          if (json.length > 0) {
            json.forEach(function (obj) {
              let newObj = obj;
              let messageID = obj.messageCipher.id;
              let plainText = sjcl.decrypt(
                passphraseOld.value,
                JSON.stringify(obj.messageCipher)
              );
              let messageCipherNew = sjcl.encrypt(
                passphraseNew.value,
                plainText,
                { mode: "gcm", ts: 128, adata: "", iter: iterations }
              );
              // let plainText = sjcl.decrypt("password", JSON.stringify(obj.messageCipher));
              // let messageCipherNew = sjcl.encrypt("password2", plainText, { mode: "gcm", ts: 128, adata: "", iter: iterations });
              // console.log(messageCipherNew)
              let messageCipherNewObj = JSON.parse(messageCipherNew);
              // console.log(messageCipherNewObj);
              messageCipherNewObj.id = messageID;
              newObj.messageCipher = messageCipherNewObj;
              // obj.messageCipher = messageCipherNewObj;
              // console.log(obj.messageCipher);
              // console.log(plainText);
              // console.log(messageCipherNewObj);
              jsonNew.push(newObj);
              messageCiphers.push(messageCipherNewObj);

              // let messageCipherJson = JSON.stringify(messageCipherNewObj);
              let chatMessageDTO = {
                toUser: user,
                fromUser: username,
                messageCipher: messageCipherNewObj,
              };
              chatMessageDTOs.push(chatMessageDTO);
            });
            // console.log(jsonNew);
          }
          // sendReencryptedMessages(JSON.stringify(jsonNew));
          console.log;
          sendReencryptedMessages(JSON.stringify(chatMessageDTOs));
          // sendReencryptedMessages(JSON.stringify(messageCiphers));

          return jsonNew;
        })
        .then((json) => {
          json.forEach(function (obj) {
            let plainText = sjcl.decrypt(
              "password2",
              JSON.stringify(obj.messageCipher)
            );
            console.log(plainText);
          });
        });
    });
}

async function getAllMessages(user) {
  let headers = new Headers();
  // headers.append('Accept','application/json')
  // headers.append('Content-Type', 'application/json');
  headers.append("Authorization", authToken);
  let response = await fetch(`${getAllMessagesURL}${user}`, {
    method: "GET",
    headers: headers,
  });
  let data = await response.json();
  return data;
}

async function getAllRegularUsers() {
  let headers = new Headers();
  // headers.append('Accept','application/json')
  // headers.append('Content-Type', 'application/json');
  headers.append("Authorization", authToken);
  let response = await fetch(`${getAllRegularUsersURL}`, {
    method: "GET",
    headers: headers,
  });
  let data = await response.json();
  return data;
}

function sendReencryptedMessages(chatMessageDTOs) {
  let headers = new Headers();
  //	console.log("Token = " + btoa("hmm" + ":" + "hmm"))

  // headers.append('Accept','application/json')
  headers.append("Content-Type", "application/json");
  headers.append("Authorization", authToken);
  fetch(reencryptURL, {
    method: "POST",
    headers: headers,
    body: chatMessageDTOs,
  }).then((response) => console.log(response));
}

handleAddToAdminForm();
handleChangePassphraseForm();
