const registerServiceWorker = async () => {
  if ("serviceWorker" in navigator) {
      try {
          const registration = await navigator.serviceWorker.register("/static/js/serviceWorker.js", {
              scope: "/",
          });
          if (registration.installing) {
              console.log("Service worker installing");
          } else if (registration.waiting) {
              console.log("Service worker installed");
          } else if (registration.active) {
              console.log("Service worker active");
          }
      } catch (error) {
          console.error("Registration failed with ${error}");
      }
  }
};
registerServiceWorker();

let _bm_xDown = 0;
let _bm_yDown = 0;

function bm_toggle_dropdown(list_id) {
    let list = document.getElementById(list_id);
    if (list.className.indexOf("show") === -1) {
    list.className += "show";
  } else {
    list.className = list.className.replace("show", "");
  }
}

function bm_overlay_off(sidebar_id) {
  document.getElementById("overlay").style.display = "none";
  bm_hide_sidebar(sidebar_id);
}

function bm_toggle_sidebar(sidebar_id) {
  let sidebar = document.getElementById(sidebar_id);
  if (sidebar.style.display === "block") {
    document.getElementById("overlay").style.display = "none";
    sidebar.style.display = "none";
    sidebar.classList.remove("mobile-sidebar");
  } else {
    document.getElementById("overlay").style.display = "block";
    sidebar.style.display = "block";
    sidebar.classList.add("mobile-sidebar");
  }
}

function bm_hide_sidebar(sidebar_id) {
  document.getElementById("overlay").style.display = "none";
  let sidebar = document.getElementById(sidebar_id);
  sidebar.style.display = "none";
  sidebar.classList.remove("mobile-sidebar")
}

function bm_sidebar_click(sidebar_id) {
  let sidebar = document.getElementById(sidebar_id);
  if(sidebar.classList.contains("mobile-sidebar")) {
    bm_hide_sidebar(sidebar_id);
    bm_hide_quickbox();
  }
}

function bm_toggle_visibility(element_id) {
  let element = document.getElementById(element_id);
  if (element.classList.contains("hidden")) {
    element.classList.remove("hidden");
  } else {
    element.classList.add("hidden");
  }

  let x = document.getElementsByClassName(element_id);
  for (let i = 0; i < x.length; i++) {
    if (x[i].classList.contains("hidden")) {
      x[i].classList.remove("hidden");
    } else {
      x[i].classList.add("hidden");
    }
  }
}

function bm_toggle_visibility_list_search(element_id) {
  let element = document.getElementById(element_id);
  element.hidden = !element.hidden;

  let x = document.getElementsByClassName("stickyheader");
  for (let i = 0; i < x.length; i++) {
    if (x[i].classList.contains("searchopened")) {
      x[i].classList.remove("searchopened");
    } else {
      x[i].classList.add("searchopened");
    }
  }
}

function bm_open_tab(element, tab_button_class, tab_class, tab_id) {
    let x = document.getElementsByClassName("tab-button");
    for (let i = 0; i < x.length; i++) {
    x[i].classList.remove("active");
  }
  element.classList.add("active");
  x = document.getElementsByClassName("tab");
  for (let i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(tab_id).style.display = "block"; 
}

function bm_show_quickbox() {
  htmx.ajax('GET', '/quickbox/all', {target:'#quickbox-notes', swap:'innerHTML'})
  document.getElementById("quickbox").style.display = "block";
}

function bm_hide_quickbox() {
  document.getElementById("quickbox").style.display = "none";
}

function bm_toggle_quickbox() {
  let quickbox = document.getElementById("quickbox");
  if(quickbox.style.display === "block") {
    bm_hide_quickbox();
  }
  else {
    bm_show_quickbox();
  }
}

function bm_show_confirm_delete(sender, title, message) {
  document.querySelector("#dialog-confirm-delete h5").innerHTML = title;
  document.querySelector("#dialog-confirm-delete p").innerHTML = message;
  document.querySelector("#dialog-confirm-delete").showModal();
  document.getElementById("modal-confirm-delete").addEventListener('click', (event) => {
      htmx.trigger(sender, 'confirmed', null);
      document.querySelector("#dialog-confirm-delete").close();
  });

  document.getElementById("modal-confirm-delete-cancel").addEventListener('click', (event) => {
    document.querySelector("#dialog-confirm-delete").close();
  });
}

function bm_show_confirm(sender, title, message) {
    document.querySelector("#dialog-confirm h5").innerHTML = title;
    document.querySelector("#dialog-confirm p").innerHTML = message;
    document.querySelector("#dialog-confirm").showModal();
    document.getElementById("modal-confirm").addEventListener('click', (event) => {
        htmx.trigger(sender, 'confirmed', null);
        document.querySelector("#dialog-confirm").close();
    });

    document.getElementById("modal-confirm-cancel").addEventListener('click', (event) => {
        document.querySelector("#dialog-confirm").close();
    });
}

function bm_item_field_add(type_field_id, widget) {
  let template = Handlebars.templates['field-' + widget]
  let fields_list = document.getElementById('fields-' + type_field_id);
  let counter = parseInt(document.getElementById('fields-' + type_field_id + '-counter').innerHTML);
  fields_list.insertAdjacentHTML('beforeend', template({type_field_id:type_field_id,counter:counter, value:""}));
  document.getElementById('fields-' + type_field_id + '-counter').innerHTML = (counter + 1).toString();
}

function bm_item_field_delete(sender, field_name) {
    document.getElementById('FieldsValuesToRemove-' + field_name).value = '1';
    sender.hidden = true;
    document.getElementById('Undelete-' + field_name).hidden = false;
    document.getElementById('FieldsValues-' + field_name).classList.add('field-opaque');
}

function bm_item_field_undelete(sender, field_name) {
    document.getElementById('FieldsValuesToRemove-' + field_name).value = '';
    sender.hidden = true;
    document.getElementById('Delete-' + field_name).hidden = false;
    document.getElementById('FieldsValues-' + field_name).classList.remove('field-opaque');
}

function bm_type_field_delete(sender, type_field_id) {
    document.getElementById('Fields-' + type_field_id + '-ToRemove').value = '1';
    sender.hidden = true;
    document.getElementById('Undelete-' + type_field_id).hidden = false;
    document.getElementById('Field-' + type_field_id).classList.add('field-opaque');
}

function bm_type_field_undelete(sender, type_field_id) {
    document.getElementById('Fields-' + type_field_id + '-ToRemove').value = '';
    sender.hidden = true;
    document.getElementById('Delete-' + type_field_id).hidden = false;
    document.getElementById('Field-' + type_field_id).classList.remove('field-opaque');
}

function bm_element_list_delete(sender, element_name, element_name_remove) {
    document.getElementById(element_name_remove).value = '1';
    sender.hidden = true;

    let btn = document.getElementById('Undelete-' + element_name);
    if(btn !== null) btn.hidden = false;

    btn = document.getElementById('Edit-' + element_name);
    if(btn !== null) btn.hidden = true;

    let x = document.getElementsByClassName(element_name + "-Col");
    for (let i = 0; i < x.length; i++) {
        x[i].classList.add("field-opaque");
    }
}

function bm_element_list_undelete(sender, element_name, element_name_remove) {
    document.getElementById(element_name_remove).value = '';
    sender.hidden = true;

    let btn = document.getElementById('Delete-' + element_name);
    if(btn !== null) btn.hidden = false;

    btn = document.getElementById('Edit-' + element_name);
    if(btn !== null) btn.hidden = false;

    let x = document.getElementsByClassName(element_name + "-Col");
    for (let i = 0; i < x.length; i++) {
        x[i].classList.remove("field-opaque");
    }
}

function bm_showMessage(msg = "") {
    if(msg !== "") {
        document.getElementById('message').innerHTML = msg;
    }
    document.getElementById('message').show();
    setTimeout(() => {
        document.getElementById('message').close();
        document.getElementById('message').innerHTML = '';
    }, 5000);
}

document.addEventListener("DOMContentLoaded", function(event){
  /*
  //Swipe on body, disabled due to conflicts
  document.querySelector('body')
  .addEventListener(
      'touchstart',
      bm_handleTouchStart,
      false
  );
  document.querySelector('body')
  .addEventListener(
      'touchmove',
      bm_handleTouchMove,
      false
  );
  */

  document.getElementById('dialog-confirm').addEventListener('click', (event) => {
        if (event.target.classList.contains("close-dialog-confirm")) {
            event.target.closest('dialog').close();
        }
  });

  document.getElementById('dialog-confirm-delete').addEventListener('click', (event) => {
    if (event.target.classList.contains("close-dialog-confirm")) {
        event.target.closest('dialog').close();
    }
  });

  document.querySelector('body').addEventListener('click', (event) => {
      console.log(event.target);
      if (event.target.classList.contains("close-dialog")) {
          event.preventDefault();
          let openDialog = event.target.closest('#dialog');
          if(openDialog !== null) {
              openDialog.close();
              openDialog.remove();
          }
      }

      if (event.target.classList.contains("copy-to-clipboard")) {
        let prefix = event.target.dataset.clipboardPrefix;
        let text = document.getElementById(event.target.dataset.clipboardFieldId).value;
          navigator.clipboard.writeText(prefix + text).then((value) => {
              bm_showMessage("<div class=\"success\"><p><i class=\"bi bi-check-circle\"></i>Item sharing url copied to clipboard</p></div>");
          }).catch((err) => {
              console.error(err);
          });
      }
  });

  document.querySelector('body').addEventListener("showModalDialog", function(evt){
    document.getElementById("dialog").showModal();
  });

  document.querySelector('body').addEventListener("closeModalDialog", function(evt){
      let openDialog = document.getElementById('dialog');
      if(openDialog !== null) {
          openDialog.close();
          openDialog.remove();
      }
  });

  document.querySelector('body').addEventListener("quickboxNoteClear", function(evt){
    document.getElementById("quickbox-notetext").value = ''
  });

  document.querySelector('body').addEventListener("closeQuickboxTransformModal", function(evt){
      bm_showMessage();
      document.getElementById('dialog').close();
      document.getElementById('dialog').remove();
    if(evt.detail.keepQuickNote === 0){
      htmx.ajax('DELETE', '/quickbox/delete/' + evt.detail.quickNoteId, {target:'#quicknote-' + evt.detail.quickNoteId, swap:'outerHTML swap:1s'})
    }
  });

  document.body.addEventListener("activateEasyMDE", function(evt){
    const easyMDE = new EasyMDE({element: document.getElementById(evt.detail.value), forceSync: true});
  });

  document.body.addEventListener("showMessage", function(evt){
    bm_showMessage();
  });

  new SlimSelect({select: '.slim-select'});
  htmx.on('htmx:afterSettle', (event) => {
    new SlimSelect({select: '.slim-select'});
  });

});

function bm_ignoreSwipe(event) {
    // if some touches come from elements with ignoreswipe class > ignore
    return Array.from(event.touches).some((t) =>
        t.target.classList.contains('noswipe')
    );
}

function bm_handleTouchStart(event) {
    if (bm_ignoreSwipe(event)) {
        _bm_xDown = undefined;
        _bm_yDown = undefined;
        return;
    }

    const firstTouch = event.touches[0];
    _bm_xDown = firstTouch.clientX;
    _bm_yDown = firstTouch.clientY;
}

function bm_handleTouchMove(event) {

    if (!_bm_xDown || !_bm_yDown) {
        return;
    }

    const xUp = event.touches[0].clientX;
    const yUp = event.touches[0].clientY;

    const xDiff = _bm_xDown - xUp;
    const yDiff = _bm_yDown - yUp;

    if (Math.abs(xDiff) > Math.abs(yDiff)) {
        /*most significant*/
        if (xDiff > 1) {
            /* left swipe */
            //console.log('app: left swipe ', true);
            bm_show_quickbox();
        } else {
            /* right swipe */
            //console.log('app: right swipe ', true);
            bm_toggle_sidebar("main-sidebar");
        }
    } else {
        if (yDiff > 1) {
            /* up swipe */
            console.log('app: up swipe ', true);
        } else {
            /* down swipe */
            console.log('app: down swipe ', true);
        }
    }

    /* reset values */
    _bm_xDown = null;
    _bm_yDown = null;
}

