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

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

            <!-- <v-text-field
              ref="appendPassword"
              v-model="obj.appendPassword"
              :append-outer-icon="reveal ? '$sockiEye' : '$sockiEyeSlash'"
              prepend-icon="$sockiKey"
              :label="$sock.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"
              >{{ $sock.t("Cancel") }}</v-btn
            >
            <v-btn
              :loading="seedingJobActive"
              :disabled="!generateStartJobAvailable"
              color="blue darken-1"
              text
              data-cy="btnStart"
              @click="generate()"
              >{{ $sock.t("StartJob") }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
    <v-row v-if="formState.ready" dense>
      <v-col dense>
        <v-form ref="form">
          <v-row dense>
            <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
            <v-col cols="12">
              <v-col cols="12">
                <div class="text-h4 text-md-h2">
                  {{ $sock.t("Welcome") }}
                </div>
              </v-col>
              <v-col cols="12">
                <div>
                  {{ $sock.t("ThankYouForEvaluating") }}
                </div>
              </v-col>
              <v-col cols="6" md="12">
                <v-btn
                  color="primary"
                  class="mt-2 mt-md-1"
                  @click="helpEvaluate()"
                  >{{ $sock.t("EvaluationGuide") }}</v-btn
                >
                <v-btn
                  color="primary"
                  class="ml-md-2 mt-2 mt-md-1"
                  :href="supportLink()"
                  target="_blank"
                  >{{ $sock.t("HelpTechSupport") }}</v-btn
                >
                <v-btn
                  color="primary"
                  class="ml-md-2 mt-2 mt-md-1"
                  data-cy="btnSeed"
                  @click="showSeedDialog()"
                  >{{ $sock.t("GenerateSampleData") }}</v-btn
                >
              </v-col>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>
  </div>
</template>
<script>
const FORM_KEY = "sock-evaluate";
export default {
  components: {},
  data() {
    return {
      seedDialog: false,
      reveal: true,
      formCustomTemplateKey: null,
      selectLists: {
        seedLevels: []
      },
      seedingJobActive: false,
      generateStartJobAvailable: 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: "sock-evaluate"
      });
    },
    supportLink() {
      return window.$gz.menu.contactSupportUrl();
    },
    showSeedDialog() {
      if (
        this.formState.readOnly ||
        window.$gz.store.getters.isSuperUser != true
      ) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          this.$sock.t("ErrorSecurityAdministratorOnlyMessage")
        );
        return;
      }
      this.generateStartJobAvailable = true;
      this.seedDialog = !this.seedDialog;
    },
    async generate() {
      const vm = this;

      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;
        }
        //point of no return, disable button so user can click again (was a huge bug)
        vm.generateStartJobAvailable = false;
        vm.seedingJobActive = true;
        //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;

        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.$sock.t("JobCompleted"));
        vm.$router.push("/login");
      } catch (error) {
        vm.seedingJobActive = false;
        window.$gz.errorHandler.handleFormError(error, vm);
        window.$gz.eventBus.$emit("notify-error", vm.$sock.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: "$sockiRocket",
    title: "Evaluate",
    helpUrl: "sock-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.$sock.t("SeedLevelSmall"), id: "small" },
//       { name: vm.$sock.t("SeedLevelMedium"), id: "medium" },
//       { name: vm.$sock.t("SeedLevelLarge"), id: "large" },
//       { name: vm.$sock.t("SeedLevelHuge"), id: "huge" }
//     ]
//   );
// }
</script>
