import "inputs";
import sha from "sha512";
import fireEvent from "event";

(() => {
   const translations = JSON.parse(
      document.getElementById("error_codes").innerText
   );

   const regcode = document.getElementById("regcode");
   regcode.value = new URL(window.location.href).searchParams.get("regcode");
   fireEvent(regcode, "change");

   function showError(element, message) {
      if (typeof element === "string")
         element = document.getElementById(element);

      if (!element) console.error("Element not found,", element);
      element.innerText = message;
      if (!message) {
         if (!element.classList.contains("invisible"))
            element.classList.add("invisible");
      } else {
         element.classList.remove("invisible");
      }
   }

   function makeid(length) {
      var text = "";
      var possible =
         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < length; i++)
         text += possible.charAt(Math.floor(Math.random() * possible.length));

      return text;
   }

   const username = document.getElementById("username");
   const name = document.getElementById("name");
   const mail = document.getElementById("mail");
   const password = document.getElementById("password");
   const passwordrep = document.getElementById("passwordrep");

   const radio_male = document.getElementById("radio-male");
   const radio_female = document.getElementById("radio-female");
   const radio_other = document.getElementById("radio-other");

   const registerButton = document.getElementById("registerbutton");
   registerButton.onclick = () => {
      console.log("Register");
      showError("error");
      let error = false;
      if (!regcode.value) {
         showError("err_regcode", translations["noregcode"]);
         error = true;
      } else {
         showError("err_regcode");
      }

      if (!username.value) {
         showError("err_username", translations["nousername"]);
         error = true;
      } else {
         showError("err_username");
      }

      if (!name.value) {
         showError("err_name", translations["noname"]);
         error = true;
      } else {
         showError("err_name");
      }

      if (!mail.value) {
         showError("err_mail", translations["nomail"]);
         error = true;
      } else {
         showError("err_mail");
      }

      if (!password.value) {
         showError("err_password", translations["nopassword"]);
         error = true;
      } else {
         showError("err_password");
      }

      if (password.value !== passwordrep.value) {
         showError("err_passwordrep", translations["nomatch"]);
         error = true;
      } else {
         showError("err_passwordrep");
      }

      if (error) return;

      let gender;

      if (radio_male.checked) {
         gender = "male";
      } else if (radio_female.checked) {
         gender = "female";
      } else {
         gender = "other";
      }

      let salt = makeid(10);

      //username, password, salt, mail, gender, name, birthday, regcode

      let body = {
         username: username.value,
         gender: gender,
         mail: mail.value,
         name: name.value,
         regcode: regcode.value,
         salt: salt,
         password: sha(salt + password.value),
      };

      fetch("/api/user/register", {
         method: "POST",
         body: JSON.stringify(body),
         headers: {
            "content-type": "application/json",
         },
      })
         .then(async (e) => {
            if (e.status !== 200)
               return Promise.reject(
                  new Error((await e.text()) || e.statusText)
               );
            return e.json();
         })
         .then((data) => {
            if (data.error) {
               if (!Array.isArray(data.error))
                  return Promise.reject(new Error(data.error));
               let ce = [];
               data.error.forEach((e) => {
                  let ef = document.getElementById("err_" + e.field);
                  if (!ef) ce.push(e);
                  else {
                     showError(ef, e.message);
                  }
               });
               if (ce.length > 0) {
                  showError("error", ce.join("<br>"));
               }
            } else {
               window.location.href = "/login";
            }
         })
         .catch((e) => {
            showError("error", e.message);
         });
   };
})();
