const logoutTimeOptions = [
  { value: "120000", label: "2 min" },
  { value: "300000", label: "5 min" },
  { value: "600000", label: "10 min" },
  { value: "1200000", label: "20 min" },
  { value: "1800000", label: "30 min" },
  { value: "3600000", label: "1 hour" },
  { value: "7200000", label: "2 hours" },
  { value: "21600000", label: "6 hours" },
  { value: "86400000", label: "1 day" },
];

let allProperties=[];

$(document).ready(async function () {
  setOptionsOfAutoLogoutTimeSelectBox(logoutTimeOptions);
});

function parsePropertiesData(stringifyData) {
  try {
    return JSON.parse(stringifyData);
  } catch (error) {
    return [];
  }
}

async function getPreferences() {
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData = await parseJSONData(sessionPreferences);
    set_preferences_form([preferencesData]);
  }else {
    sendPreferencesRequest({
      get_preferences_for_property_user: true,
      property_id: sessionStorage.getItem("propertyId"),
    });
  }
  $("#prefmodal").modal("show");
}

async function sendPreferencesRequest(data) {
  $.ajax({
    url: "/include/preferences/set_preferences.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.get_preferences_for_property_user) {
        set_preferences_form(resp?.data);
      }  else if (
        data?.edit_user_property_preferences ||
        data?.add_user_property_preferences
      ) {
        sessionStorage.removeItem("preferences");
        $("#prefmodal").modal("hide");
        window.location.reload();
      } else if (data?.get_user_menu_for_property_user) {
      }
    },
    error: function (xhr, status, error) {
      console.log("error : ", error);
      console.log("xhr", xhr);

      if (xhr?.responseJSON?.error)
        showHeaderToastMessage(xhr?.responseJSON?.error);
      else showHeaderToastMessage(error);
    },
  });
}

function set_preferences_form(data) {
  let preferences = data?.length > 0 ? data[0] : null;
  document.getElementById("themeMode").value =
    preferences?.theme_mode || "";
  document.getElementById("preferencesId").value = preferences?.id || null;
  document.getElementById("timeFormat").value = preferences?.time_format || "";
  document.getElementById("autoLogoutTime").value =
    preferences?.auto_logout_time || "";
  document.getElementById("startPage").value =
    preferences?.app_start_page || "";
  document.getElementById("isCardView").value =
    preferences?.is_card_view || "0";
  document.getElementById("startProperty").value =
    preferences?.starting_property_id || "";
}

function submitPreferencesValues() {
  const id = document.getElementById("preferencesId").value;
  const preferences = {
    theme_mode: document.getElementById("themeMode").value,
    time_format: document.getElementById("timeFormat").value,
    auto_logout_time: document.getElementById("autoLogoutTime").value,
    app_start_page: document.getElementById("startPage").value,
    starting_property_id: document.getElementById("startProperty").value,
    is_card_view: document.getElementById("isCardView").value,
    property_id: sessionStorage.getItem("propertyId"),
  };  

  if (id) {
    preferences["id"] = id;
    preferences["edit_user_property_preferences"] = true;
  } else preferences["add_user_property_preferences"] = true;
  sendPreferencesRequest(preferences);
  console.log("Preferences to Submit:", preferences);
}

function setOptionsOfAllStartingPageSelectBox(data) {
  const selectBox = document.getElementById("startPage");
  selectBox.innerHTML = '<option value="" disabled >Select start page</option>';
  data.forEach((resource) => {
    const option = document.createElement("option");
    option.value = resource.slug;
    option.textContent = resource.name;
    selectBox.appendChild(option);
  });
}

function setOptionsOfAutoLogoutTimeSelectBox(data) {
  const selectBox = document.getElementById("autoLogoutTime");
  selectBox.innerHTML = '<option value="" disabled >Select auto-logout time</option>';
  data.forEach((time) => {
    const option = document.createElement("option");
    option.value = time.value;
    option.textContent = time.label;
    selectBox.appendChild(option);
  });
}

function showHeaderToastMessage(errorMessage) {
  document.getElementById("headerToastMessage").style.display = "block";
  document.getElementById("headerToastMessageErrorMessage").textContent =
    errorMessage;
  var toastEl = document.getElementById("myToast");
  var toast = new bootstrap.Toast(toastEl, {
    delay: 3000,
    autohide: false,
  });
  toast.show();

  setTimeout(() => {
    closeHeaderToastMessage();
  }, 4000);
}

function closeHeaderToastMessage() {
  const toastEl = document.getElementById("headerToastMessage");
  toastEl.style.display = "none";
}
