<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" offset-md="3">
            <v-col cols="12">
              <div class="text-h4 text-md-h2 mb-2">{{ $ay.t("Welcome") }}</div>
            </v-col>
            <v-col cols="12">
              <v-btn @click="helpEvaluate()" class="my-8 mr-16">{{
                $ay.t("EvaluationGuide")
              }}</v-btn>
              <v-btn :href="supportLink()" target="blank" class="my-8 mr-12">{{
                $ay.t("HelpTechSupport")
              }}</v-btn>
            </v-col>
            <v-col cols="12">
              <div class="text-h5 mt-8 mb-2">
                {{ $ay.t("GenerateSampleData") }}
              </div>
              <v-col cols="12" sm="6" v-if="formState.readOnly">
                <div class="text-h6 mt-8 warning--text">
                  {{ $ay.t("ErrorSecurityAdministratorOnlyMessage") }}
                </div>
              </v-col>
              <v-col cols="12" sm="6">
                <v-select
                  v-model="obj.seedLevel"
                  :items="selectLists.seedLevels"
                  :rules="[form().required(this, 'seedLevel')]"
                  @input="fieldValueChanged('seedLevel')"
                  ref="seedLevel"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :disabled="formState.readOnly"
                  :label="$ay.t('SeedLevel')"
                ></v-select>
              </v-col>
              <v-col cols="12" sm="6">
                <v-text-field
                  v-model="obj.timeZoneOffset"
                  :readonly="formState.readOnly"
                  :disabled="formState.readOnly"
                  :rules="[
                    form().decimalValid(this, 'timeZoneOffset'),
                    form().required(this, 'timeZoneOffset')
                  ]"
                  :label="$ay.t('UserTimeZoneOffset')"
                  type="number"
                  ref="timeZoneOffset"
                  @input="fieldValueChanged('timeZoneOffset')"
                ></v-text-field>
              </v-col>

              <v-col cols="12">
                <v-btn
                  :loading="seedingJobActive"
                  :disabled="formState.readOnly"
                  @click="generate()"
                  class="my-8 mr-4"
                  >{{ $ay.t("StartJob") }}</v-btn
                >
              </v-col>
            </v-col>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

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

const FORM_KEY = "ay-evaluate";
export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.obj.timeZoneOffset =
        Math.floor(new Date().getTimezoneOffset() / 60) * -1;
      //get rights to generate sample data and erase db I guess
      vm.rights = window.$gz.role.getRights(window.$gz.type.TrialSeeder);
      //set form readonly if it's so
      vm.formState.readOnly = !vm.rights.change;
      generateMenu(vm);
      vm.formState.ready = true;
      vm.formState.loading = false;
      window.$gz.eventBus.$on("menu-click", clickHandler);
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },

  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      formCustomTemplateKey: null,
      selectLists: {
        seedLevels: []
      },
      seedingJobActive: false,
      obj: {
        seedLevel: "small",
        timeZoneOffset: 0
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject()
    };
  },

  methods: {
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    helpEvaluate() {
      window.$gz.eventBus.$emit("menu-click", {
        key: "app:help",
        data: "ay-evaluate"
      });
    },
    supportLink() {
      return window.$gz.menu.contactSupportUrl();
    },
    async generate() {
      let vm = this;

      if (vm.formState.readOnly) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          vm.$ay.t("ErrorSecurityAdministratorOnlyMessage")
        );
        return;
      }
      try {
        //Does the database need to be erased?
        let res = await window.$gz.api.get("license/database-empty");
        //We never expect there to be no data here
        if (!res.hasOwnProperty("data")) {
          throw res;
        }
        if (res.data != true) {
          let dialogResult = await window.$gz.dialog.confirmGeneric(
            "AdminEraseDatabaseWarning",
            "warning"
          );
          if (dialogResult == false) {
            return;
          }

          dialogResult = await window.$gz.dialog.confirmGeneric(
            "AdminEraseDatabaseLastWarning",
            "error"
          );
          if (dialogResult == false) {
            return;
          }
          //call erase
          await window.$gz.api.upsert(
            "license/permanently-erase-all-data",
            "I understand"
          );
        }

        //call seed route
        let jobId = await window.$gz.api.upsert(
          `trial/seed/${vm.obj.seedLevel}/${vm.obj.timeZoneOffset}`
        );
        if (jobId.error) {
          throw jobId.error;
        }
        jobId = jobId.jobId; //it's in a sub key
        //indicate loading by setting on button
        vm.seedingJobActive = true;

        /*  /// <summary>
    /// Job status for opsjobs
    /// </summary>
    public enum JobStatus : int
    {
        Absent=0,
        Sleeping = 1,
        Running = 2,
        Completed = 3,
        Failed = 4
    } */
        let jobStatus = 1;
        //get status

        while (vm.seedingJobActive == true) {
          await window.$gz.util.sleepAsync(1000);
          //check if done
          jobStatus = await window.$gz.api.get(
            `job-operations/status/${jobId}`
          );
          if (jobStatus.error) {
            throw jobStatus.error;
          }
          jobStatus = jobStatus.data;
          if (jobStatus == 4 || jobStatus == 0) {
            throw "Seeding job failed";
          }
          if (jobStatus == 3) {
            vm.seedingJobActive = false;
          }
        }

        //Here if it's completed successfully
        window.$gz.eventBus.$emit("notify-success", vm.$ay.t("JobCompleted"));
        vm.$router.push("/login");
      } catch (error) {
        vm.seedingJobActive = false;
        window.$gz.errorHandler.handleFormError(error, vm);
        window.$gz.eventBus.$emit("notify-error", vm.$ay.t("JobFailed"));
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-rocket",
    title: "Evaluate",
    helpUrl: "ay-evaluate",
    menuItems: []
  };

  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([
    "Welcome",
    "GenerateSampleData",
    "EvaluationGuide",
    "HelpTechSupport",
    "SeedLevel",
    "SeedLevelSmall",
    "SeedLevelMedium",
    "SeedLevelLarge",
    "SeedLevelHuge",
    "StartJob",
    "AdminEraseDatabaseWarning",
    "AdminEraseDatabaseLastWarning",
    "UserTimeZoneOffset",
    "JobCompleted",
    "JobFailed",
    "ErrorSecurityAdministratorOnlyMessage"
  ]);
}

/////////////////////////////////
//
//
function populateSelectionLists(vm) {
  vm.selectLists.seedLevels.push(
    ...[
      { name: vm.$ay.t("SeedLevelSmall"), id: "small" },
      { name: vm.$ay.t("SeedLevelMedium"), id: "medium" },
      { name: vm.$ay.t("SeedLevelLarge"), id: "large" },
      { name: vm.$ay.t("SeedLevelHuge"), id: "huge" }
    ]
  );
}
</script>
