<template>
  <v-container fluid>
    <v-row justify="center">
      <v-dialog v-model="testDialog" persistent max-width="600px">
        <v-card>
          <v-card-title>
            <span class="headline">{{ $ay.t("TestSMTPSettings") }}</span>
          </v-card-title>
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="testAddress"
                    :label="$ay.t('TestToAddress')"
                    required
                    hint="test_send_to@example.com"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="testDialog = false">{{
              $ay.t("Cancel")
            }}</v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="testConfiguration()"
              :disabled="!testAddress"
              >{{ $ay.t("OK") }}</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 :errorBoxMessage="formState.errorBoxMessage"></gz-error>

            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-checkbox
                v-model="obj.smtpDeliveryActive"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :label="$ay.t('SmtpDeliveryActive')"
                :persistent-hint="true"
                ref="smtpDeliveryActive"
                :error-messages="
                  form().serverErrors(this, 'smtpDeliveryActive')
                "
                @change="fieldValueChanged('smtpDeliveryActive')"
              ></v-checkbox>
            </v-col>
            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                v-model="obj.smtpServerAddress"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :clearable="!formState.readOnly"
                @click:clear="fieldValueChanged('smtpServerAddress')"
                :label="$ay.t('SmtpServerAddress')"
                :rules="[form().required(this, 'smtpServerAddress')]"
                :error-messages="form().serverErrors(this, 'smtpServerAddress')"
                ref="smtpServerAddress"
                :data-cy="!!$ay.dev ? 'smtpServerAddress' : false"
                @input="fieldValueChanged('smtpServerAddress')"
              ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                v-model="obj.smtpAccount"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :clearable="!formState.readOnly"
                @click:clear="fieldValueChanged('smtpAccount')"
                :label="$ay.t('SmtpAccount')"
                :rules="[form().required(this, 'smtpAccount')]"
                :error-messages="form().serverErrors(this, 'smtpAccount')"
                ref="smtpAccount"
                :data-cy="!!$ay.dev ? 'smtpAccount' : false"
                @input="fieldValueChanged('smtpAccount')"
              ></v-text-field>
            </v-col>

            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                v-model="obj.smtpPassword"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :clearable="!formState.readOnly"
                @click:clear="fieldValueChanged('smtpPassword')"
                :label="$ay.t('SmtpPassword')"
                :rules="[form().required(this, 'smtpPassword')]"
                :error-messages="form().serverErrors(this, 'smtpPassword')"
                ref="smtpPassword"
                :data-cy="!!$ay.dev ? 'smtpPassword' : false"
                @input="fieldValueChanged('smtpPassword')"
              ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-select
                v-model="obj.connectionSecurity"
                :items="selectLists.NotifyMailSecurity"
                item-text="name"
                item-value="id"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :label="$ay.t('ConnectionSecurity')"
                ref="connectionSecurity"
                :data-cy="!!$ay.dev ? 'connectionSecurity' : false"
                :rules="[
                  form().integerValid(this, 'connectionSecurity'),
                  form().required(this, 'connectionSecurity')
                ]"
                :error-messages="
                  form().serverErrors(this, 'connectionSecurity')
                "
                @input="fieldValueChanged('connectionSecurity')"
              ></v-select>
            </v-col>
            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                v-model="obj.smtpServerPort"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :clearable="!formState.readOnly"
                @click:clear="fieldValueChanged('smtpServerPort')"
                :label="$ay.t('SmtpServerPort')"
                :rules="[
                  form().integerValid(this, 'smtpServerPort'),
                  form().required(this, 'smtpServerPort')
                ]"
                :error-messages="form().serverErrors(this, 'smtpServerPort')"
                ref="smtpServerPort"
                :data-cy="!!$ay.dev ? 'smtpServerPort' : false"
                @input="fieldValueChanged('smtpServerPort')"
                type="number"
              ></v-text-field>
            </v-col>

            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                v-model="obj.notifyFromAddress"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :clearable="!formState.readOnly"
                @click:clear="fieldValueChanged('notifyFromAddress')"
                :label="$ay.t('NotifyFromAddress')"
                :rules="[form().required(this, 'notifyFromAddress')]"
                :error-messages="form().serverErrors(this, 'notifyFromAddress')"
                ref="notifyFromAddress"
                :data-cy="!!$ay.dev ? 'notifyFromAddress' : false"
                @input="fieldValueChanged('notifyFromAddress')"
              ></v-text-field>
            </v-col>

            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                v-model="obj.ayaNovaServerURL"
                :readonly="formState.readOnly"
                :disabled="formState.readOnly"
                :clearable="!formState.readOnly"
                @click:clear="fieldValueChanged('ayaNovaServerURL')"
                :label="$ay.t('AyaNovaServerURL')"
                :rules="[form().required(this, 'ayaNovaServerURL')]"
                :error-messages="form().serverErrors(this, 'ayaNovaServerURL')"
                ref="ayaNovaServerURL"
                :data-cy="!!$ay.dev ? 'ayaNovaServerURL' : false"
                @input="fieldValueChanged('ayaNovaServerURL')"
              ></v-text-field>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>
  </v-container>
</template>

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

const FORM_KEY = "ops-backup";

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

      vm.rights = window.$gz.role.getRights(window.$gz.type.GlobalOps);
      vm.formState.readOnly = !vm.rights.change;
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      await vm.getDataFromApi();
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      testAddress: null,
      testDialog: false,
      selectLists: {
        NotifyMailSecurity: []
      },
      obj: {
        id: 1,
        concurrency: 0,
        smtpDeliveryActive: null,
        smtpServerAddress: null,
        smtpAccount: null,
        smtpPassword: null,
        connectionSecurity: null,
        smtpServerPort: null,
        notifyFromAddress: null,
        ayaNovaServerURL: null
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject()
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        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: {
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;
      let url = "global-ops-notification-setting";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.eventBus.$emit("notify-error", vm.$ay.t("ErrorAPI2010"));
            window.$gz._.delay(function() {
              vm.$router.go(-1);
            }, 2000);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async submit() {
      let vm = this;
      try {
        if (vm.canSave) {
          vm.formState.loading = true;
          let url = "global-ops-notification-setting";
          window.$gz.form.deleteAllErrorBoxErrors(vm);
          let res = await window.$gz.api.upsert(url, vm.obj);

          vm.formState.loading = false;
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            vm.obj.concurrency = res.data.concurrency;
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });
          }
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async testConfiguration() {
      let vm = this;
      vm.formState.loading = true;
      vm.testDialog = false;
      let url = `global-ops-notification-setting/test-smtp-settings/${vm.testAddress}`;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.upsert(url, {});
        vm.formState.loading = false;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          window.$gz.eventBus.$emit("notify-success", vm.$ay.t("JobCompleted"));
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
async 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;
      case "test":
        m.vm.testDialog = true;
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-bullhorn",
    title: "NotificationSettings",
    helpUrl: "form-ops-notification-settings",
    formData: {
      ayaType: window.$gz.type.OpsNotificationSettings
    },
    formData: {},
    menuItems: []
  };

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

    menuOptions.menuItems.push({
      title: "TestSMTPSettings",
      icon: "fa-vial",
      surface: false,
      key: FORM_KEY + ":test",
      vm: vm
    });
  }

  menuOptions.menuItems.push({
    title: "NotifyQueue",
    icon: null,
    data: "ops-notify-queue",
    key: "app:nav"
  });

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

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

//////////////////////////////////////////////////////////
//
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "TestSMTPSettings",
    "TestToAddress",
    "SmtpDeliveryActive",
    "SmtpServerAddress",
    "SmtpAccount",
    "SmtpPassword",
    "ConnectionSecurity",
    "SmtpServerPort",
    "NotifyFromAddress",
    "AyaNovaServerURL",
    "JobCompleted",
    "NotifyQueue"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  await window.$gz.enums.fetchEnumList("NotifyMailSecurity"); //prefetch
  //populate
  vm.selectLists.NotifyMailSecurity = window.$gz.enums.getSelectionList(
    "NotifyMailSecurity"
  );
}
</script>
