<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <button
          type="submit"
          disabled
          style="display: none"
          aria-hidden="true"
        ></button>
        <v-row>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
          <template v-if="tfaEnabled">
            <v-col cols="12">
              <v-card data-cy="tfa" class="mx-auto my-12" max-width="600">
                <v-card-title>{{ $ay.t("AuthConnectAppTitle") }}</v-card-title>
                <v-card-text>
                  <v-btn color="accent" @click="disable()">{{
                    $ay.t("AuthDisableTwoFactor")
                  }}</v-btn>
                </v-card-text>
              </v-card>
            </v-col>
          </template>
          <template v-else>
            <v-col cols="12">
              <v-card class="mx-auto my-12" max-width="600">
                <v-card-title>{{ $ay.t("AuthConnectAppTitle") }}</v-card-title>
                <v-card-subtitle
                  >{{ $ay.t("AuthConnectAppSubTitle") }}
                </v-card-subtitle>
                <v-card-text>
                  <div class="text-center my-10">
                    <img alt="Embedded QR Code" :src="qCode" />
                  </div>
                  {{ $ay.t("AuthConnectAppManualEntry") }}
                  <span class="text-subtitle-2 ml-2">{{ obj.s }}</span>
                  <v-text-field
                    class="mt-10"
                    v-model="pin"
                    :label="$ay.t('AuthEnterPin')"
                    :error-messages="form().serverErrors(this, 'pin')"
                    ref="pin"
                    @input="fieldValueChanged('pin')"
                    data-cy="tfa"
                    autofocus
                    @keyup.enter="authenticate"
                  ></v-text-field>
                </v-card-text>
                <v-card-actions>
                  <v-spacer></v-spacer>

                  <v-btn color="primary" text @click="authenticate()">{{
                    $ay.t("AuthVerifyCode")
                  }}</v-btn>
                </v-card-actions>
              </v-card>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

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

const FORM_KEY = "home-security";
const API_BASE_URL = "auth/";

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.fullRightsObject();
      generateMenu(vm);
      vm.formState.ready = true;
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true,
        loading: false,
        readOnly: false
      });
      window.$gz.eventBus.$on("menu-click", clickHandler);

      //fetch tfa secret and display here if tfa not enabled currently
      if (!this.tfaEnabled) {
        let res = await window.$gz.api.get("auth/totp");
        if (res.error) {
          throw new Error(res.error);
        } else {
          this.obj = res.data;
        }
      }

      //------------------
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      obj: {
        s: null, // = u.TotpSecret,
        qr: null // = qrCodeImageAsBase64
      },
      pin: null,
      tfaEnabled: window.$gz.store.state.tfaEnabled,
      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;
    // },
    qCode: function() {
      return `data:image/png;base64,${this.obj.qr}`;
    }
  },
  methods: {
    // 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);
      }
    },
    async disable() {
      let vm = this;

      vm.formState.loading = true;

      //clear any errors vm might be around from previous submit
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.post(
          `auth/totp-disable/${vm.$store.state.userId}`
        );

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          window.$gz.store.commit("setTfaEnabled", false);
          await window.$gz.dialog.displayLTModalNotificationMessage(
            "AuthTwoFactorDisabled"
          );
          vm.$router.push("/home-user-settings");

          //Only a post, no data returned
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        vm.loading = false;
      }
    },
    async authenticate() {
      let vm = this;

      vm.formState.loading = true;

      //clear any errors vm might be around from previous submit
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.post("auth/totp-validate", {
          pin: vm.pin
        });

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data.ok == true) {
            window.$gz.store.commit("setTfaEnabled", true);
            //all ok, 2fa enabled
            await window.$gz.dialog.displayLTModalNotificationMessage(
              "AuthConnectCompleted"
            );
            vm.$router.push("/home-user-settings");
          } else {
            window.$gz.eventBus.$emit(
              "notify-warning",
              this.$ay.t("AuthPinInvalid")
            );
          }

          //Only a post, no data returned
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        vm.loading = false;
      }
    }
  }
};

/////////////////////////////
//
//
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: "$ayiLock",
    title: "AuthTwoFactor",
    helpUrl: "home-tfa",
    formData: {
      ayaType: window.$gz.type.UserOptions
    },
    menuItems: []
  };

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

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "AuthConnectAppTitle",
    "AuthConnectAppSubTitle",
    "AuthConnectAppManualEntry",
    "AuthEnterPin",
    "AuthTwoFactor",
    "AuthPinInvalid",
    "AuthConnectCompleted",
    "AuthDisableTwoFactor",
    "AuthTwoFactorDisabled",
    "AuthVerifyCode"
  ]);
}
</script>
