import { createApp } from "vue";
import PickPostalCode from "ChillMainAssets/vuejs/PickPostalCode/PickPostalCode";
import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n";
import { appMessages } from "ChillMainAssets/vuejs/PickEntity/i18n";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

const i18n = _createI18n(appMessages);

function loadOnePicker(el, input, uniqId, city) {
  const app = createApp({
    template:
      '<pick-postal-code @select-city="onCitySelected" @removeCity="onCityRemoved" :picked="city"></pick-postal-code>',
    components: {
      PickPostalCode,
    },
    data() {
      return {
        city: city,
      };
    },
    methods: {
      onCitySelected(city) {
        this.city = city;
        input.value = city.id;
      },
      onCityRemoved(city) {
        this.city = null;
        input.value = "";
      },
    },
  })
    .use(i18n)
    .mount(el);
}

function loadDynamicPickers(element) {
  let apps = element.querySelectorAll('[data-module="pick-postal-code"]');

  apps.forEach(function (el) {
    const uniqId = el.dataset.uniqid,
      input = document.querySelector(`input[data-input-uniqid="${uniqId}"]`),
      cityIdValue = input.value === "" ? null : input.value;
    if (cityIdValue !== null) {
      makeFetch("GET", `/api/1.0/main/postal-code/${cityIdValue}.json`).then(
        (city) => {
          loadOnePicker(el, input, uniqId, city);
        },
      );
    } else {
      loadOnePicker(el, input, uniqId, null);
    }
  });
}

document.addEventListener("DOMContentLoaded", function (e) {
  loadDynamicPickers(document);
});
