<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <v-col>
            <v-stepper v-model="currentStep" vertical>
              <v-stepper-step :complete="currentStep > 1" step="1">
                {{ $ay.t("Welcome") }}
                <!-- <small>Summarize if needed</small> -->
              </v-stepper-step>

              <v-stepper-content step="1">
                <v-card class="mb-12"></v-card>
                <v-btn color="primary" @click="currentStep = 2">{{
                  $ay.t("Continue")
                }}</v-btn>
                <v-btn text>{{ $ay.t("Cancel") }}</v-btn>
              </v-stepper-content>

              <v-stepper-step :complete="currentStep > 2" step="2"
                >Second step</v-stepper-step
              >

              <v-stepper-content step="2">
                <v-card
                  color="grey lighten-1"
                  class="mb-12"
                  height="200px"
                ></v-card>
                <v-btn color="primary" @click="currentStep = 3">{{
                  $ay.t("Continue")
                }}</v-btn>
                <v-btn text>{{ $ay.t("Cancel") }}</v-btn>
              </v-stepper-content>

              <v-stepper-step :complete="currentStep > 3" step="3"
                >Third step</v-stepper-step
              >

              <v-stepper-content step="3">
                <v-card
                  color="grey lighten-1"
                  class="mb-12"
                  height="200px"
                ></v-card>
                <v-btn color="primary" @click="currentStep = 4">{{
                  $ay.t("Continue")
                }}</v-btn>
                <v-btn text>{{ $ay.t("Cancel") }}</v-btn>
              </v-stepper-content>

              <v-stepper-step step="4">Fourth step</v-stepper-step>
              <v-stepper-content step="4">
                <v-card
                  color="grey lighten-1"
                  class="mb-12"
                  height="200px"
                ></v-card>
                <v-btn color="primary" @click="currentStep = 1">{{
                  $ay.t("Cancel")
                }}</v-btn>
                <v-btn text>{{ $ay.t("Cancel") }}</v-btn>
              </v-stepper-content>
            </v-stepper>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "adm-launch";
const API_BASE_URL = null;
const FORM_CUSTOM_TEMPLATE_KEY = null;

export default {
  created() {
    let vm = this;
    initForm(vm)
      .then(() => {
        //this form is alwasy the Manager account no exceptions so all rights are valid
        vm.rights = window.$gz.role.fullRightsObject();
        vm.formState.ready = true;
        window.$gz.eventBus.$on("menu-click", clickHandler);

        vm.getDataFromApi();
      })
      .catch(err => {
        vm.formState.ready = true;
        window.$gz.errorHandler.handleFormError(err, vm);
      });
  },
  beforeRouteLeave(to, from, next) {
    if (this.formState.dirty) {
      window.$gz.dialog.confirmLeaveUnsaved().then(dialogResult => {
        if (dialogResult == true) {
          next();
        } else {
          next(false);
        }
      });
    } else {
      next();
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        translations: []
      },
      currentStep: 1,
      obj: {},
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject()
    };
  },
  //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: {
    completeStep() {
      return 1;
    },
    translation() {
      return window.$gz.translation;
    },

    form() {
      return window.$gz.form;
    },

    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    getDataFromApi() {
      let vm = this;
      //------------
      //TODO: for now just return
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true,
        loading: false
      });
      return;

      //--------------

      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);

      window.$gz.api
        .get(url)
        .then(res => {
          if (res.error) {
            //Not found?
            if (res.error.code == "2010") {
              //notify not found error then navigate backwards
              window.$gz.eventBus.$emit(
                "notify-error",
                vm.$ay.t("ErrorAPI2010")
              );
              // navigate backwards
              window.$gz._.delay(function() {
                vm.$router.go(-1);
              }, 2000);
            }
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            vm.obj = res.data;

            //Update the form status
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false,
              valid: true,
              loading: false
            });
            //modify the menu as necessary
            generateMenu(vm);
          }
        })
        .catch(function handleGetDataFromAPIError(error) {
          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
          window.$gz.errorHandler.handleFormError(error, vm);
        });
    },
    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);
        window.$gz.api
          .upsert(url, vm.obj)
          .then(res => {
            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.locale;

              if (vm.obj.languageOverride) {
                l.languageOverride = vm.obj.languageOverride;
              }

              if (vm.obj.timeZoneOverride) {
                l.timeZoneOverride = vm.obj.timeZoneOverride;
              }

              if (vm.obj.currencyName) {
                l.currencyName = vm.obj.currencyName;
              }

              if (vm.obj.hour12) {
                l.hour12 = vm.obj.hour12;
              }

              window.$gz.store.commit("setLocale", l);
            }
          })
          .catch(function handleSubmitError(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;

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

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-rocket",
    title: vm.$ay.t("Launch"),
    helpUrl: "form-adm-launch",
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: vm.$ay.t("Save"),
      icon: "fa-save",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  //   //change password and login
  //   menuOptions.menuItems.push({
  //     title: vm.$ay.t("SetLoginPassword"),
  //     icon: "fa-key",
  //     data: "home-password",
  //     key: "app:nav"
  //   });

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
function initForm(vm) {
  return new Promise(async function(resolve, reject) {
    // (async function() {
    try {
      await fetchTranslatedText(vm);
      // await populateSelectionLists(vm);
    } catch (err) {
      reject(err);
    }
    resolve();
    // })();
  });
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
function fetchTranslatedText(vm) {
  return window.$gz.translation.cacheTranslations(["Launch", "Welcome"]);
}

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