import request from "../../shared/request";
import getFormData from "../../shared/formdata";
Handlebars.registerHelper("humangender", function (value, options) {
   switch (value) {
      case 1:
         return "male";
      case 2:
         return "female";
      case 3:
         return "other";
      default:
      case 0:
         return "none";
   }
});

// Deprecated since version 0.8.0
Handlebars.registerHelper("formatDate", function (datetime, format) {
   return new Date(datetime).toLocaleString();
});

(() => {
   const tableb = document.getElementById("table-body");

   function setTitle(title) {
      document.getElementById("sitename").innerText = title;
   }

   const cc = document.getElementById("custom_data");
   const ccc = document.getElementById("custom_data_cont");

   function setCustomCard(content) {
      if (!content) {
         cc.innerHTML = "";
         ccc.style.display = "none";
      } else {
         cc.innerHTML = content;
         ccc.style.display = "";
      }
   }

   const error_cont = document.getElementById("error_cont");
   const error_msg = document.getElementById("error_msg");

   function catchError(error) {
      error_cont.style.display = "";
      error_msg.innerText = error.message;
      console.log(error);
   }

   async function renderUser() {
      console.log("Rendering User");
      setTitle("User");
      const listt = Handlebars.compile(
         document.getElementById("template-user-list").innerText
      );

      async function loadList() {
         let data = await request("/api/admin/user", "GET");
         tableb.innerHTML = listt({
            users: data,
         });
      }

      window.userOnChangeType = (id) => {
         request("/api/admin/user?id=" + id, "PUT")
            .then(() => loadList())
            .catch(catchError);
      };

      window.deleteUser = (id) => {
         request("/api/admin/user?id=" + id, "DELETE")
            .then(() => loadList())
            .catch(catchError);
      };

      await loadList();
   }

   async function renderPermissions(client_id, client_name) {
      const listt = Handlebars.compile(
         document.getElementById("template-permission-list").innerText
      );
      const formt = Handlebars.compile(
         document.getElementById("template-permission-form").innerText
      );
      setCustomCard();
      async function loadList() {
         try {
            let data = await request(
               "/api/admin/permission?client=" + client_id,
               "GET"
            );
            tableb.innerHTML = listt({
               client_id: client_id,
               client_name: client_name,
               permissions: data,
            });
         } catch (err) {
            catchError(err);
         }
      }

      window.gotoClients = () => {
         renderClient();
      };

      window.deletePermission = (id) => {
         request("/api/admin/permission?id=" + id, "DELETE")
            .then(() => loadList())
            .catch(catchError);
      };

      window.createPermission = () => {
         try {
            setCustomCard(formt({ client_id: client_id }));
         } catch (err) {
            console.log("Err", err);
         }
      };

      window.createPermissionSubmit = (elm) => {
         console.log(elm);
         let data = getFormData(elm);
         console.log(data);
         request("/api/admin/permission", "POST", data)
            .then(() => setCustomCard())
            .then(() => loadList())
            .catch(catchError);
      };
      await loadList();
   }

   async function renderClient() {
      console.log("Rendering Client");
      setTitle("Client");

      const listt = Handlebars.compile(
         document.getElementById("template-client-list").innerText
      );
      const formt = Handlebars.compile(
         document.getElementById("template-client-form").innerText
      );

      let clients = [];
      async function loadList() {
         let data = await request("/api/admin/client", "GET");
         clients = data;
         tableb.innerHTML = listt({
            clients: data,
         });
      }

      window.permissionsClient = (id) => {
         renderPermissions(id, clients.find((e) => e._id === id).name);
      };

      window.deleteClient = (id) => {
         request("/api/admin/client/id=" + id, "DELETE")
            .then(() => loadList())
            .catch(catchError);
      };

      window.createClientSubmit = (elm) => {
         console.log(elm);
         let data = getFormData(elm);
         console.log(data);
         let id = data.id;
         delete data.id;
         if (id && id !== "") {
            request("/api/admin/client?id=" + id, "PUT", data)
               .then(() => setCustomCard())
               .then(() => loadList())
               .catch(catchError);
         } else {
            request("/api/admin/client", "POST", data)
               .then(() => setCustomCard())
               .then(() => loadList())
               .catch(catchError);
         }
      };

      window.createClient = () => {
         setCustomCard(formt());
      };

      window.editClient = (id) => {
         let client = clients.find((e) => e._id === id);
         if (!client) return catchError(new Error("Client does not exist!!"));
         setCustomCard(formt(client));
      };

      await loadList().catch(catchError);
   }

   async function renderRegCode() {
      console.log("Rendering RegCode");
      setTitle("RegCode");

      const listt = Handlebars.compile(
         document.getElementById("template-regcode-list").innerText
      );

      async function loadList() {
         let data = await request("/api/admin/regcode", "GET");
         tableb.innerHTML = listt({
            regcodes: data,
         });
      }

      window.deleteRegcode = (id) => {
         request("/api/admin/regcode?id=" + id, "DELETE")
            .then(() => loadList())
            .catch(catchError);
      };

      window.createRegcode = () => {
         request("/api/admin/regcode", "POST")
            .then(() => loadList())
            .catch(catchError);
      };

      await loadList().catch(catchError);
   }

   const type = new URL(window.location.href).searchParams.get("type");
   switch (type) {
      case "client":
         renderClient().catch(catchError);
         break;
      case "regcode":
         renderRegCode().catch(catchError);
         break;
      case "user":
      default:
         renderUser().catch(catchError);
         break;
   }
})();
