<template>
  <div>
    <v-row dense justify="center">
      <v-dialog v-model="testDialog" persistent max-width="600px">
        <v-card>
          <v-card-title>
            <span class="text-h5">{{ $sock.t("TestSMTPSettings") }}</span>
          </v-card-title>
          <v-card-text>
            <v-text-field
              v-model="testAddress"
              dense
              :label="$sock.t('TestToAddress')"
              required
              hint="test_send_to@example.com"
            ></v-text-field>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="testDialog = false">{{
              $sock.t("Cancel")
            }}</v-btn>
            <v-btn
              color="blue darken-1"
              text
              :disabled="!testAddress"
              @click="testConfiguration()"
              >{{ $sock.t("OK") }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
    <v-row v-if="formState.ready" dense>
      <v-col>
        <v-form ref="form">
          <v-row dense>
            <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>

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

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

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

            <v-col cols="12" sm="6" lg="4" xl="3">
              <v-text-field
                ref="sockeyeServerURL"
                v-model="obj.sockeyeServerURL"
                dense
                :readonly="formState.readOnly"
                :label="$sock.t('SockeyeServerURL')"
                :rules="[form().required(this, 'sockeyeServerURL')]"
                :error-messages="form().serverErrors(this, 'sockeyeServerURL')"
                data-cy="sockeyeServerURL"
                @input="fieldValueChanged('sockeyeServerURL')"
              ></v-text-field>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>
  </div>
</template>
<script>
const FORM_KEY = "ops-notification-settings";
export default {
  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,
        sockeyeServerURL: null
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject()
    };
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const 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
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(
        window.$gz.type.OpsNotificationSettings
      );
      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);
  },
  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() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get("global-ops-notification-setting");
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          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() {
      const vm = this;
      try {
        if (vm.canSave) {
          vm.formState.loading = true;
          window.$gz.form.deleteAllErrorBoxErrors(vm);
          const res = await window.$gz.api.upsert(
            "global-ops-notification-setting",
            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() {
      const vm = this;
      vm.formState.loading = true;
      vm.testDialog = false;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.upsert(
          `global-ops-notification-setting/test-smtp-settings/${vm.testAddress}`,
          {}
        );
        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.$sock.t("JobCompleted")
          );
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const 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) {
  const menuOptions = {
    isMain: true,
    readOnly: vm.formState.readOnly,
    icon: "$sockiBullhorn",
    title: "OpsNotificationSettings",
    helpUrl: "ops-notification-system",
    formData: {
      sockType: window.$gz.type.OpsNotificationSettings
    },
    menuItems: []
  };

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

    menuOptions.menuItems.push({
      title: "TestSMTPSettings",
      icon: "$sockiVial",
      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();
  await populateSelectionLists(vm);
}

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

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