<template>
  <v-row v-if="formState.ready" dense>
    <v-col>
      <v-form ref="form">
        <v-row dense>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-select
              ref="translationId"
              v-model="obj.translationId"
              dense
              :items="selectLists.translations"
              item-text="name"
              item-value="id"
              :readonly="formState.readOnly"
              :label="$ay.t('Translation')"
              :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
              ref="emailAddress"
              v-model="obj.emailAddress"
              :readonly="formState.readOnly"
              :label="$ay.t('UserEmailAddress')"
              :error-messages="form().serverErrors(this, 'emailAddress')"
              data-cy="emailAddress"
              @input="fieldValueChanged('emailAddress')"
            ></gz-email>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'Phone1')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-phone
              ref="phone1"
              v-model="obj.phone1"
              :readonly="formState.readOnly"
              :label="$ay.t('UserPhone1')"
              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
              ref="phone2"
              v-model="obj.phone2"
              :readonly="formState.readOnly"
              :label="$ay.t('UserPhone2')"
              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
              ref="phone3"
              v-model="obj.phone3"
              :readonly="formState.readOnly"
              :label="$ay.t('UserPageAddress')"
              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
              ref="mapUrlTemplate"
              v-model="obj.mapUrlTemplate"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('MapUrlTemplate')"
              :error-messages="form().serverErrors(this, 'mapUrlTemplate')"
              data-cy="mapUrlTemplate"
              :hint="obj.mapUrlTemplate == null ? 'Google maps' : ''"
              persistent-hint
              @input="fieldValueChanged('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-checkbox
              ref="hour12"
              v-model="obj.hour12"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('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-checkbox
              ref="nativeDateTimeInput"
              v-model="nativeDateTimeInput"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('NativeDateTimeInput')"
              data-cy="nativeDateTimeInput"
              @change="nativeDateTimeInputChanged()"
            ></v-checkbox>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="currencyName"
              v-model="obj.currencyName"
              dense
              :hint="
                obj.currencyName == null || obj.currencyName == ''
                  ? locale().getCurrencyName()
                  : ''
              "
              persistent-hint
              :readonly="formState.readOnly"
              :label="$ay.t('CurrencyCode')"
              :error-messages="form().serverErrors(this, 'currencyName')"
              append-outer-icon="$ayiQuestionCircle"
              @input="fieldValueChanged('currencyName')"
              @click:append-outer="goHelp()"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="languageOverride"
              v-model="obj.languageOverride"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('LanguageCode')"
              :error-messages="form().serverErrors(this, 'languageOverride')"
              :hint="locale().getResolvedLanguage()"
              persistent-hint
              append-outer-icon="$ayiQuestionCircle"
              @input="fieldValueChanged('languageOverride')"
              @click:append-outer="goHelp()"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="timeZoneOverride"
              v-model="obj.timeZoneOverride"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('TimeZone')"
              :error-messages="form().serverErrors(this, 'timeZoneOverride')"
              :hint="locale().getResolvedTimeZoneName()"
              persistent-hint
              append-outer-icon="$ayiQuestionCircle"
              @input="fieldValueChanged('timeZoneOverride')"
              @click:append-outer="goHelp()"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <span class="text-caption">
              {{ $ay.t("UserColor") }}
            </span>
            <v-color-picker
              ref="uiColor"
              v-model="obj.uiColor"
              :readonly="formState.readOnly"
              hide-mode-switch
              mode="hexa"
              :error-messages="form().serverErrors(this, 'uiColor')"
              @input="fieldValueChanged('uiColor')"
            ></v-color-picker>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "user-settings";
const API_BASE_URL = "user-option/";
const FORM_CUSTOM_TEMPLATE_KEY = "UserOptions";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        translations: [],
        mapUrls: window.$gz.util.mapProviderUrls()
      },
      activeTranslationId: null,
      darkMode: this.$store.state.darkMode,
      nativeDateTimeInput: this.$store.state.nativeDateTimeInput,
      obj: {
        id: 0,
        concurrency: 0,
        emailAddress: null,
        phone1: null,
        phone2: null,
        phone3: null,
        mapUrlTemplate: null,
        uiColor: "#000000ff",
        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()
    };
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const 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
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.fullRightsObject();
      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 or duplicate to new 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);
  },
  methods: {
    goHelp() {
      window.open(window.$gz.api.helpUrl() + "ay-start-localization", "_blank");
    },
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    form() {
      return window.$gz.form;
    },
    darkModeChanged() {
      const 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"
      );
      window.$gz.eventBus.$emit("notify-success", vm.$ay.t("OK"));
    },
    nativeDateTimeInputChanged() {
      const vm = this;
      //vm.nativeDateTimeInput = !vm.nativeDateTimeInput;
      vm.$store.commit("setNativeDateTimeInput", vm.nativeDateTimeInput);
      window.$gz.eventBus.$emit("notify-success", vm.$ay.t("OK"));
    },
    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() {
      this.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(this);
      try {
        const res = await window.$gz.api.get(
          API_BASE_URL + this.$store.state.userId
        );
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(this);
          }
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        } else {
          this.obj = res.data;
          this.activeTranslationId = res.data.translationId;
          window.$gz.form.setFormState({
            vm: this,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(this);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, this);
      }
    },
    async submit() {
      if (this.canSave) {
        this.formState.loading = true;
        window.$gz.form.deleteAllErrorBoxErrors(this);
        try {
          const res = await window.$gz.api.upsert(
            API_BASE_URL + this.$store.state.userId,
            this.obj
          );
          this.formState.loading = false;
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            this.obj.concurrency = res.data.concurrency;
            window.$gz.form.setFormState({
              vm: this,
              dirty: false
            });
            //Set values in store so they are updated immediately for user
            const l = this.$store.state.userOptions;
            l.languageOverride = this.obj.languageOverride;
            l.timeZoneOverride = this.obj.timeZoneOverride;
            l.currencyName = this.obj.currencyName;
            l.hour12 = this.obj.hour12;
            //l.uiColor = this.obj.uiColor;
            l.emailAddress = this.obj.emailAddress;
            l.mapUrlTemplate = this.obj.mapUrlTemplate;
            window.$gz.store.commit("setUserOptions", l);

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

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const 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) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiUserCog",
    title: "UserSettings",
    helpUrl: "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({
    title: "AuthTwoFactor",
    icon: "$ayiLock",
    data: "home-security",
    key: "app:nav:SECURITY"
  });

  menuOptions.menuItems.push({ divider: true, inset: false });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

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

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

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