<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-select
              v-model="obj.translationId"
              :items="selectLists.translations"
              item-text="name"
              item-value="id"
              :readonly="formState.readOnly"
              :label="$ay.t('Translation')"
              ref="translationId"
              :error-messages="form().serverErrors(this, 'translationId')"
              @input="fieldValueChanged('translationId')"
            ></v-select>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-email
              v-model="obj.emailAddress"
              :readonly="formState.readOnly"
              :label="$ay.t('UserEmailAddress')"
              :error-messages="form().serverErrors(this, 'emailAddress')"
              ref="emailAddress"
              @input="fieldValueChanged('emailAddress')"
              data-cy="emailAddress"
            ></gz-email>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'Phone1')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-phone
              v-model="obj.phone1"
              :readonly="formState.readOnly"
              :disabled="formState.readOnly"
              :label="$ay.t('UserPhone1')"
              ref="phone1"
              data-cy="phone1"
              :error-messages="form().serverErrors(this, 'phone1')"
              @input="fieldValueChanged('phone1')"
            ></gz-phone>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'Phone2')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-phone
              v-model="obj.phone2"
              :readonly="formState.readOnly"
              :disabled="formState.readOnly"
              :label="$ay.t('UserPhone2')"
              ref="phone2"
              data-cy="phone2"
              :error-messages="form().serverErrors(this, 'phone2')"
              @input="fieldValueChanged('phone2')"
            ></gz-phone>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'Phone3')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-phone
              v-model="obj.phone3"
              :readonly="formState.readOnly"
              :disabled="formState.readOnly"
              :label="$ay.t('UserPageAddress')"
              ref="phone3"
              data-cy="phone3"
              :error-messages="form().serverErrors(this, 'phone3')"
              @input="fieldValueChanged('phone3')"
            ></gz-phone>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.mapUrlTemplate"
              :readonly="formState.readOnly"
              :label="$ay.t('MapUrlTemplate')"
              :error-messages="form().serverErrors(this, 'mapUrlTemplate')"
              ref="mapUrlTemplate"
              @input="fieldValueChanged('mapUrlTemplate')"
              data-cy="mapUrlTemplate"
            ></v-text-field>
            <v-select
              :items="selectLists.mapUrls"
              item-text="name"
              item-value="value"
              @input="mapUrlSelectionChanged"
            ></v-select>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.currencyName"
              hint="e.g. USD, EUR, GBP, AUD, CAD etc"
              :readonly="formState.readOnly"
              :label="$ay.t('CurrencyCode')"
              :rules="[form().required(this, 'currencyName')]"
              :error-messages="form().serverErrors(this, 'currencyName')"
              ref="currencyName"
              @input="fieldValueChanged('currencyName')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.hour12"
              :readonly="formState.readOnly"
              :label="$ay.t('Hour12')"
              ref="hour12"
              :error-messages="form().serverErrors(this, 'hour12')"
              @change="fieldValueChanged('hour12')"
            ></v-checkbox>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.languageOverride"
              :placeholder="locale().getBrowserFirstLanguage()"
              :readonly="formState.readOnly"
              :label="$ay.t('LanguageCode')"
              :error-messages="form().serverErrors(this, 'languageOverride')"
              ref="languageOverride"
              @input="fieldValueChanged('languageOverride')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.timeZoneOverride"
              :placeholder="locale().getBrowserTimeZoneName()"
              :readonly="formState.readOnly"
              :label="$ay.t('TimeZone')"
              :error-messages="form().serverErrors(this, 'timeZoneOverride')"
              ref="timeZoneOverride"
              @input="fieldValueChanged('timeZoneOverride')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <!-- https://vuetifyjs.com/en/components/color-pickers -->
            <span class="v-label v-label--active theme--light">
              {{ $ay.t("UserColor") }}
            </span>
            <v-color-picker
              v-model="obj.uiColor"
              :readonly="formState.readOnly"
              hide-mode-switch
              mode="hexa"
              :error-messages="form().serverErrors(this, 'uiColor')"
              ref="uiColor"
              @input="fieldValueChanged('uiColor')"
            ></v-color-picker>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

<script>
import EmailControl from "../components/email-control.vue";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "home-user-settings";
const API_BASE_URL = "user-option/";
const FORM_CUSTOM_TEMPLATE_KEY = "UserOptions"; //<- Should always be CoreBizObject AyaType name here

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.fullRightsObject(); //getRights(window.$gz.type.UserOptions);
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //UserOptions never creates a new one so this code is a little different than other forms
      //NOTE: FOR NOW GOING TO ASSUME THIS FORM WILL ONLY EVER BE USED TO EDIT *CURRENT* USER'S USEROPTIONS
      //SO NOT FOR EDITING OTHER USERS, WILL ASSUME THE USER EDITOR FORM FOR MANAGEMENT WILL HAVE A COMPACT VERSION
      //OF THESE SAME FIELDS FOR THAT PURPOSE
      //SO ALWAYS USER CURRENT LOGGED IN USER ID FOR THIS
      //id 0 means create a new record don't load one but thats not applicable here

      await vm.getDataFromApi();
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        translations: [],
        mapUrls: window.$gz.util.mapProviderUrls()
      },
      activeTranslationId: null,
      darkMode: this.$store.state.darkMode,
      obj: {
        /*concurrency": 7490431,
    "translationId": 1,
    "emailAddress": null,
    "uiColor": "#000000",
    "languageOverride": null,
    "timeZoneOverride": null,
    "currencyName": "USD",
    "hour12": true,
    "userId": 1 */
        id: 0,
        concurrency: 0,
        emailAddress: null,
        phone1: null,
        phone2: null,
        phone3: null,
        mapUrlTemplate: null,
        uiColor: null,
        languageOverride: null,
        timeZoneOverride: null,
        currencyName: null,
        hour12: null,
        translationId: null
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject()
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        let canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  methods: {
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    form() {
      return window.$gz.form;
    },
    darkModeChanged() {
      let vm = this;
      vm.darkMode = !vm.darkMode;
      vm.$store.commit("setDarkMode", vm.darkMode);
      vm.$vuetify.theme.dark = vm.darkMode;
      window.$gz.eventBus.$emit(
        "menu-change-item-icon",
        FORM_KEY + ":darkmode",
        vm.darkMode ? "$ayiSun" : "$ayiMoon"
      );
    },
    mapUrlSelectionChanged(val) {
      this.obj.mapUrlTemplate = val;
      this.fieldValueChanged("mapUrlTemplate");
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;
      //always fetch on this form for the current logged in user id
      let url = API_BASE_URL + vm.$store.state.userId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          //Not found?
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          vm.activeTranslationId = res.data.translationId;

          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          //modify the menu as necessary
          generateMenu(vm);
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit() {
      let vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;

        //always submit from this form for the current logged in user id
        let url = API_BASE_URL + vm.$store.state.userId;

        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        try {
          let res = await window.$gz.api.upsert(url, vm.obj);

          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //UserOptions is never a POST as it always exists and can't be deleted so always a PUT

            //Handle "put" of an existing record (UPDATE)
            vm.obj.concurrency = res.data.concurrency;
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });

            //Set values in store so they are updated immediately for user
            let l = vm.$store.state.userOptions;
            l.languageOverride = vm.obj.languageOverride;
            l.timeZoneOverride = vm.obj.timeZoneOverride;
            l.currencyName = vm.obj.currencyName;
            l.hour12 = vm.obj.hour12;
            l.uiColor = vm.obj.uiColor;
            l.emailAddress = vm.obj.emailAddress;
            l.mapUrlTemplate = vm.obj.mapUrlTemplate;
            window.$gz.store.commit("setUserOptions", l);

            if (
              vm.activeTranslationId &&
              vm.activeTranslationId != vm.obj.translationId
            ) {
              await window.$gz.translation.updateCache();
              vm.activeTranslationId = vm.obj.translationId;
            }
          }
        } catch (error) {
          vm.formState.loading = false;
          window.$gz.errorHandler.handleFormError(error, vm);
        }
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "darkmode":
        m.vm.darkModeChanged();
        break;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiUserCog",
    title: "UserSettings",
    helpUrl: "form-home-user-settings",
    formData: {
      ayaType: window.$gz.type.UserOptions
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }
  menuOptions.menuItems.push({ divider: true, inset: false });
  menuOptions.menuItems.push({
    title: "DarkMode",
    icon: vm.darkMode ? "$ayiSun" : "$ayiMoon",
    surface: true,
    key: FORM_KEY + ":darkmode",
    vm: vm
  });

  //change password and login
  menuOptions.menuItems.push({
    title: "SetLoginPassword",
    icon: "$ayiKey",
    data: "home-password",
    key: "app:nav"
  });
  menuOptions.menuItems.push({ divider: true, inset: false });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "CurrencyCode",
    "LanguageCode",
    "TimeZone",
    "Hour12",
    "UserEmailAddress",
    "UserColor",
    "Translation",
    "DarkMode",
    "MapUrlTemplate",
    "UserPhone1",
    "UserPhone2",
    "UserPageAddress"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //http://localhost:7575/api/v8/translation/list
  let res = await window.$gz.api.get("translation/list");
  if (res.error) {
    vm.formState.serverError = res.error;
    window.$gz.form.setErrorBoxErrors(vm);
    //window.$gz.errorHandler.handleFormError(res.error, vm);
  } else {
    vm.selectLists.translations = res.data;
  }
}
</script>

<style></style>
