const contactDataBlock = document.querySelector("div.location-form-contact");
const addressBlock = document.querySelector("div.location-form-address");
const locationType = document.getElementById(
  "chill_mainbundle_location_locationType",
);

const getSelectedAttributes = (select, attr) =>
  select.selectedOptions[0].getAttribute(attr);

const removeRequired = (formBlock) => {
  formBlock
    .querySelectorAll("label")
    .forEach((l) => l.classList.remove("required"));
  formBlock
    .querySelectorAll("input")
    .forEach((i) => i.removeAttribute("required"));
};

const addRequired = (formBlock) => {
  formBlock
    .querySelectorAll("label")
    .forEach((l) => l.classList.add("required"));
  formBlock
    .querySelectorAll("input")
    .forEach((i) => i.setAttribute("required", ""));
};

const onLocationTypeChange = () => {
  console.log(getSelectedAttributes(locationType, "data-address"));
  console.log(getSelectedAttributes(locationType, "data-contact"));
  switch (getSelectedAttributes(locationType, "data-address")) {
    case "optional":
    default:
      removeRequired(addressBlock);
      addressBlock.classList.remove("d-none");
      break;
    case "required":
      addRequired(addressBlock);
      addressBlock.classList.remove("d-none");
      break;
    case "never":
      removeRequired(addressBlock);
      addressBlock.classList.add("d-none");
      break;
  }
  switch (getSelectedAttributes(locationType, "data-contact")) {
    case "optional":
    default:
      removeRequired(contactDataBlock);
      contactDataBlock.classList.remove("d-none");
      break;
    case "required":
      addRequired(contactDataBlock);
      contactDataBlock.classList.remove("d-none");
      break;
    case "never":
      removeRequired(contactDataBlock);
      contactDataBlock.classList.add("d-none");
      break;
  }
};

document.addEventListener("DOMContentLoaded", (_e) => {
  onLocationTypeChange();
  locationType.addEventListener("change", onLocationTypeChange);
});
