"use strict";
(function () {
  let
    control_deleteButtons = document.querySelectorAll(".identificationdocument__delete__button"),
    control_fileInput = document.querySelector(".identification-document__upload__file"),
    control_filename = document.querySelector(".identification-document__filename"),
    control_image = document.querySelector(".identification-document__a__img"),
    control_imageBase64Url = document.querySelector(".identification-document__base64"),
    control_imageLink = document.querySelector(".identification-document__a"),
    control_uploadButton = document.querySelector(".identification-document__upload__button")
    ;

  function _bindEvents() {
    control_uploadButton.addEventListener("click", function () {
      control_fileInput.click();
    });

    control_fileInput.addEventListener("change", function (event) {
      const file = event.target.files[0];
      if (file) {
        control_filename.value = file.name;
        const reader = new FileReader();
        reader.onload = function (e) {
          const base64StringUrl = e.target.result;
          control_imageLink.href = base64StringUrl;
          control_image.src = base64StringUrl;
        };
        reader.readAsDataURL(file);
      } else {
        console.log('No file selected');
      }
    });

    control_deleteButtons?.forEach(btn => {
      btn.addEventListener("click", _deleteIdentificationDocument);
    });
  }

  function _deleteIdentificationDocument(e) {
    jfa.components.dialog.confirm({
      message: "Are you sure you want to delete this Identification Document?",
      callbackyes: function () {
        let btn = e.target.closest("button");
        let url = new URL(window.location.origin + '/Principal/IdentificationDocument/IdentificationDocument/' + btn.dataset.uid);
        url.searchParams.append("IdentificationDocument_UID", btn.dataset.uid);
        url.searchParams.append("handler", "DeleteIdentificationDocument");
        jfa.utilities.request.post(url, {})
          .then(resp => {
            if (resp.ok === true) {
              jfa.page.reload();
            }
          })
          .catch(err => console.error(err));
      }
    });
  }

  function _init() {
    _bindEvents();
    _initFiles();
  }

  function _initFiles() {
    if (control_imageBase64Url.value) {
      const fileContent = control_imageBase64Url.value.split(',')[1];
      const filename = control_filename.value;
      const file = new File([fileContent], filename);
      const dataTransfer = new DataTransfer();
      dataTransfer.items.add(file);
      const fileList = dataTransfer.files;
      control_fileInput.files = fileList;
    }
  }

  _init();
})();