<template>
  <div>
    <v-row justify="center">
      <v-dialog v-model="seedDialog" persistent max-width="800px">
        <v-card>
          <v-card-title>
            <span class="text-h5 mb-2">{{ $ay.t("GenerateSampleData") }}</span>
          </v-card-title>
          <v-card-text>
            <div v-if="formState.readOnly" class="text-h6 mt-8 warning--text">
              {{ $ay.t("ErrorSecurityAdministratorOnlyMessage") }}
            </div>
            <!-- <v-select
              ref="seedLevel"
              v-model="obj.seedLevel"
              :items="selectLists.seedLevels"
              :rules="[form().required(this, 'seedLevel')]"
              item-text="name"
              item-value="id"
              :readonly="formState.readOnly"
              :label="$ay.t('SeedLevel')"
              @input="fieldValueChanged('seedLevel')"
            ></v-select> -->
            <v-text-field
              ref="timeZoneOffset"
              v-model="obj.timeZoneOffset"
              :readonly="formState.readOnly"
              :rules="[
                form().decimalValid(this, 'timeZoneOffset'),
                form().required(this, 'timeZoneOffset')
              ]"
              :label="$ay.t('UserTimeZoneOffset')"
              type="number"
              @input="fieldValueChanged('timeZoneOffset')"
            ></v-text-field>

            <gz-email
              ref="emailAddress"
              v-model="obj.forceEmail"
              :label="$ay.t('EvaluateForceEmail')"
              @input="fieldValueChanged('forceEmail')"
            ></gz-email>

            <!-- <v-text-field
              ref="appendPassword"
              v-model="obj.appendPassword"
              :append-outer-icon="reveal ? '$ayiEye' : '$ayiEyeSlash'"
              prepend-icon="$ayiKey"
              :label="$ay.t('EvaluateAppendPassword')"
              :type="reveal ? 'text' : 'password'"
              @input="fieldValueChanged('appendPassword')"
              @click:append-outer="reveal = !reveal"
            ></v-text-field> -->
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn
              v-if="!seedingJobActive"
              color="blue darken-1"
              text
              @click="seedDialog = false"
              >{{ $ay.t("Cancel") }}</v-btn
            >
            <v-btn
              :loading="seedingJobActive"
              color="blue darken-1"
              text
              data-cy="btnStart"
              @click="generate()"
              >{{ $ay.t("StartJob") }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
    <v-row v-if="formState.ready">
      <v-col>
        <v-form ref="form">
          <v-row>
            <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
            <v-col cols="12">
              <v-col cols="12">
                <div class="text-h4 text-md-h2">
                  {{ $ay.t("Welcome") }}
                </div>
              </v-col>
              <v-col cols="12">
                <div>
                  {{ $ay.t("ThankYouForEvaluating") }}
                </div>
              </v-col>
              <v-col cols="6" md="12">
                <v-btn
                  large
                  color="primary"
                  class="mt-2 mt-md-1"
                  @click="helpEvaluate()"
                  >{{ $ay.t("EvaluationGuide") }}</v-btn
                >
                <v-btn
                  large
                  color="primary"
                  class="ml-md-2 mt-2 mt-md-1"
                  :href="supportLink()"
                  target="_blank"
                  >{{ $ay.t("HelpTechSupport") }}</v-btn
                >
                <v-btn
                  large
                  color="primary"
                  class="ml-md-2 mt-2 mt-md-1"
                  data-cy="btnSeed"
                  @click="seedDialog = !seedDialog"
                  >{{ $ay.t("GenerateSampleData") }}</v-btn
                >
              </v-col>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>
  </div>
</template>
<script>
const FORM_KEY = "ay-evaluate";
export default {
  components: {},
  data() {
    return {
      seedDialog: false,
      reveal: true,
      formCustomTemplateKey: null,
      selectLists: {
        seedLevels: []
      },
      seedingJobActive: false,
      obj: {
        seedLevel: "small",
        timeZoneOffset: 0,
        e2e: false,
        forceEmail: null,
        appendPassword: null
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject()
    };
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.obj.timeZoneOffset =
        Math.floor(new Date().getTimezoneOffset() / 60) * -1;
      vm.rights = window.$gz.role.getRights(window.$gz.type.TrialSeeder);
      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);
  },
  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() {
      const vm = this;

      if (
        vm.formState.readOnly ||
        window.$gz.store.getters.isSuperUser != true
      ) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          vm.$ay.t("ErrorSecurityAdministratorOnlyMessage")
        );
        return;
      }
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let dialogResult = await window.$gz.dialog.confirmGeneric(
          "AdminEraseDatabaseWarning",
          "warning"
        );
        if (dialogResult == false) {
          return;
        }
        dialogResult = await window.$gz.dialog.confirmGeneric(
          "AdminEraseDatabaseLastWarning",
          "dire"
        );
        if (dialogResult == false) {
          return;
        }

        //call the FULL (including taxcodes) erase before seeding
        window.$gz.erasingDatabase = true; //flags notify poll to suspend as user may be gone
        let r = await window.$gz.api.upsert(
          "license/permanently-erase-all-data",
          "I understand"
        );
        if (r.error) {
          throw new Error(window.$gz.errorHandler.errorToString(r, vm));
        }
        window.$gz.erasingDatabase = false;

        //start the seeding
        let jobId = await window.$gz.api.upsert("trial/seed", vm.obj);

        if (jobId.error) {
          throw new Error(window.$gz.errorHandler.errorToString(jobId, vm));
        }
        jobId = jobId.jobId;
        vm.seedingJobActive = true;
        let jobStatus = 1;
        while (vm.seedingJobActive == true) {
          await window.$gz.util.sleepAsync(5000);
          jobStatus = await window.$gz.api.get(
            `job-operations/status/${jobId}`
          );
          if (jobStatus.error) {
            throw new Error(
              window.$gz.errorHandler.errorToString(jobStatus, vm)
            );
          }
          jobStatus = jobStatus.data;
          if (jobStatus == 4 || jobStatus == 0) {
            throw new Error("Seeding job failed");
          }
          if (jobStatus == 3) {
            vm.seedingJobActive = false;
          }
        }
        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;
  }
  const 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() {
  const menuOptions = {
    isMain: true,
    icon: "$ayiRocket",
    title: "Evaluate",
    helpUrl: "ay-evaluate",
    menuItems: []
  };

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

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "Welcome",
    "GenerateSampleData",
    "EvaluationGuide",
    "HelpTechSupport",
    //"SeedLevel",
    //"SeedLevelSmall",
    //"SeedLevelMedium",
    //"SeedLevelLarge",
    // "SeedLevelHuge",
    "StartJob",
    "AdminEraseDatabaseWarning",
    "AdminEraseDatabaseLastWarning",
    "UserTimeZoneOffset",
    "JobCompleted",
    "JobFailed",
    "ErrorSecurityAdministratorOnlyMessage",
    "ThankYouForEvaluating",
    //"EvaluateAppendPassword",
    "EvaluateForceEmail"
  ]);
}

// /////////////////////////////////
// //
// //
// 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>
