<template>
  <page-section :section-title="$t('pageTransfer.smtp.smtpTitle')">
    <b-row class="smtp-warning mb-5">
      <b-col xs="12" sm="12">
        <div class="switch-group">
          <label for="authenticationSwitch">{{
            $t('pageTransfer.smtp.authorization')
          }}</label>
          <b-form-checkbox
            id="authenticationSwitch"
            v-model="form.is_need_auth"
            data-test-id="checkbox-authorization"
            switch
            :disabled="loading || isNotAdmin"
            @change="onChangeAuthCheckbox($event)"
          >
            <span v-if="form.is_need_auth">
              {{ $t('global.status.enabled') }}
            </span>
            <span v-else>{{ $t('global.status.disabled') }}</span>
          </b-form-checkbox>
        </div>
      </b-col>
      <b-col xs="12" sm="6">
        <b-form-group
          :label="$t('pageTransfer.smtp.username')"
          label-for="smtp-name"
        >
          <b-form-input
            id="smtp-name"
            v-model="form.username"
            type="text"
            :state="getValidationState($v.form.username)"
            :disabled="loading || isNotAdmin || !form.is_need_auth"
            @input="$v.form.username.$touch()"
          />
          <b-form-invalid-feedback role="alert">
            <template v-if="!$v.form.username.required">
              {{ $t('global.form.fieldRequired') }}
            </template>
            <template v-else-if="!$v.form.username.maxLength">
              {{ $t('global.form.lengthMustBeBetween', { min: 1, max: 256 }) }}
            </template>
            <template v-else-if="!$v.form.username.pattern">
              {{ $t('global.form.invalidFormat') }}
            </template>
          </b-form-invalid-feedback>
        </b-form-group></b-col
      >
      <b-col xs="12" sm="6">
        <b-form-group
          :label="$t('pageTransfer.smtp.password')"
          label-for="smtp-password"
        >
          <input-password-toggle>
            <b-form-input
              id="smtp-password"
              v-model="form.password"
              type="password"
              :state="getValidationState($v.form.password)"
              :disabled="loading || isNotAdmin || !form.is_need_auth"
              @input="$v.form.password.$touch()"
            />
            <b-form-invalid-feedback role="alert">
              <template v-if="!$v.form.password.required">
                {{ $t('global.form.fieldRequired') }}
              </template>
              <template
                v-if="
                  !$v.form.password.minLength || !$v.form.password.maxLength
                "
              >
                {{
                  $t('pageUserManagement.modal.passwordMustBeBetween', {
                    min: 8,
                    max: 20,
                  })
                }}
              </template>
            </b-form-invalid-feedback>
          </input-password-toggle>
        </b-form-group>
      </b-col>
      <b-col xs="12" sm="6">
        <b-form-group
          :label="$t('pageTransfer.smtp.host')"
          label-for="smtp-host"
        >
          <b-form-input
            id="smtp-host"
            v-model="form.host"
            :state="getValidationState($v.form.host)"
            :disabled="loading || isNotAdmin"
            @input="$v.form.host.$touch()"
          />
          <b-form-invalid-feedback role="alert">
            <template v-if="!$v.form.host.required">
              {{ $t('global.form.fieldRequired') }}
            </template>
            <template v-if="!$v.form.host.ipAddress">
              {{ $t('global.form.invalidFormat') }}
            </template>
          </b-form-invalid-feedback>
        </b-form-group>
      </b-col>
      <b-col xs="12" sm="6">
        <b-form-group
          :label="$t('pageTransfer.smtp.port')"
          label-for="smtp-port"
        >
          <b-form-input
            id="smtp-port"
            v-model="form.port"
            type="number"
            :state="getValidationState($v.form.port)"
            :disabled="loading || isNotAdmin"
            @input="$v.form.port.$touch()"
          />
          <b-form-invalid-feedback role="alert">
            <template v-if="!$v.form.port.required">
              {{ $t('global.form.fieldRequired') }}
            </template>
            <template v-if="!$v.form.port.pattern">
              {{ $t('global.form.invalidFormat') }}
            </template>
          </b-form-invalid-feedback>
        </b-form-group>
      </b-col>
      <b-col xs="12" sm="12">
        <div class="switch-group">
          <label for="sslSwitch">{{
            $t('pageTransfer.smtp.sslEnabled')
          }}</label>
          <b-form-checkbox
            id="sslSwitch"
            v-model="form.is_need_ssl"
            data-test-id="checkbox-ssl"
            switch
            :disabled="isNotAdmin"
          >
            <span v-if="form.is_need_ssl">
              {{ $t('global.status.enabled') }}
            </span>
            <span v-else>{{ $t('global.status.disabled') }}</span>
          </b-form-checkbox>
        </div>
      </b-col>
      <b-col xs="4" class="d-flex justify-content-between align-items-start">
        <b-button
          variant="secondary"
          :disabled="loading || isNotAdmin"
          @click="sendMail"
        >
          {{ $t('pageTransfer.smtp.testMessage') }}
        </b-button>

        <b-button
          variant="primary"
          :disabled="loading || isNotAdmin"
          @click="saveSmtp"
        >
          {{ $t('global.action.save') }}
        </b-button>
      </b-col>
    </b-row>
    <b-row>
      <b-col>
        <div class="text-right">
          <b-button
            variant="primary"
            :disabled="loading || isNotAdmin"
            @click="initAddModal()"
          >
            <icon-add />
            {{ $t('global.action.add') }}
          </b-button>
        </div>
        <b-table
          responsive="md"
          hover
          :busy="loading"
          :fields="fields"
          :items="subscribers"
          :empty-text="$t('global.table.emptyMessage')"
          show-empty
        >
          <!-- table actions column -->
          <template #cell(actions)="{ item }">
            <table-row-action
              v-for="(action, index) in item.actions"
              :key="index"
              :value="action.value"
              :enabled="action.enabled"
              :title="action.title"
              @click-table-action="onTableAction($event, item)"
            >
              <template #icon>
                <icon-trashcan
                  v-if="action.value === 'delete'"
                  :data-test-id="`smtp-tableRowAction-delete-${index}`"
                />
              </template>
            </table-row-action>
          </template>
        </b-table>
      </b-col>
    </b-row>
  </page-section>
</template>

<script>
import PageSection from '@/components/_sila/Global/PageSection';
import BVToastMixin from '@/components/_sila/Mixins/BVToastMixin';
import TableRowAction from '@/components/_sila/Global/TableRowAction';
import LoadingBarMixin, {
  loading,
} from '@/components/_sila/Mixins/LoadingBarMixin';

import IconAdd from '@carbon/icons-vue/es/add--alt/20';
import IconTrashcan from '@carbon/icons-vue/es/trash-can/20';
import InputPasswordToggle from '@/components/_sila/Global/InputPasswordToggle';
import {
  helpers,
  maxLength,
  minLength,
  required,
  requiredIf,
} from 'vuelidate/lib/validators';
import VuelidateMixin from '@/components/_sila/Mixins/VuelidateMixin.js';
import { isoNtpRegex } from '@/utilities/_sila/regexConstants';
import { isoPortRegex } from '@/utilities/_sila/regexConstants';

export default {
  name: 'Smtp',
  components: {
    IconAdd,
    IconTrashcan,
    PageSection,
    TableRowAction,
    InputPasswordToggle,
  },
  mixins: [BVToastMixin, LoadingBarMixin, VuelidateMixin],

  data() {
    return {
      loading,
      form: {
        username: '',
        password: '',
        host: '',
        port: '',
        is_need_auth: false,
        is_need_ssl: true,
      },
      fields: [
        {
          key: 'host',
          label: this.$t('pageTransfer.table.userName'),
        },
        { key: 'actions', label: '', tdClass: 'text-right' },
      ],
    };
  },
  computed: {
    settings() {
      return this.$store.getters['smtpStore/settings'];
    },
    subscribers() {
      return this.$store.getters['smtpStore/subscribers'].map((subscriber) => {
        return {
          ...subscriber,
          actions: [
            {
              value: 'delete',
              title: this.$t('pageTransfer.smtp.delSubscriber'),
            },
          ],
        };
      });
    },
    isNotAdmin() {
      return (
        this.$store.getters['authentication/role'] === 'ReadOnly' ||
        this.$store.getters['authentication/role'] === 'Operator'
      );
    },
  },
  watch: {
    settings() {
      this.setForm();
    },
  },
  created() {
    this.startLoader();
    Promise.all([
      this.$store.dispatch('smtpStore/getSettings'),
      this.$store.dispatch('smtpStore/getSubscribers'),
    ]).finally(() => {
      this.setForm();
      this.endLoader();
    });
  },
  validations() {
    return {
      form: {
        username: {
          required: requiredIf(function () {
            return this.form.is_need_auth;
          }),
          maxLength: maxLength(254),
          pattern: helpers.regex('pattern', /^([a-zA-Z_][a-zA-Z0-9_]*)/),
        },
        password: {
          required: requiredIf(function () {
            return this.form.is_need_auth;
          }),
          minLength: minLength(8),
          maxLength: maxLength(20),
        },
        host: {
          required,
          pattern: helpers.regex('pattern', isoNtpRegex),
        },
        port: {
          pattern: helpers.regex('pattern', isoPortRegex),
        },
      },
    };
  },
  methods: {
    onChangeAuthCheckbox($event) {
      if (!$event) {
        this.resetAuthForm();
      }
    },
    onTableAction($event, { host }) {
      if ($event === 'delete') {
        this.deleteSubscriber(host);
      }
    },
    deleteSubscriber(host) {
      this.startLoader();
      this.$store
        .dispatch('smtpStore/deleteSubscriber', host)
        .then((success) => this.successToast(success))
        .catch(({ message }) => this.errorToast(message))
        .finally(() => this.endLoader());
    },
    initAddModal() {
      this.$bvModal.show('modal-smtp');
    },
    saveSmtp() {
      this.$v.$touch();
      if (this.$v.$invalid) return;

      this.startLoader();
      if (!this.form.is_need_auth) {
        // eslint-disable-next-line no-unused-vars
        const { username, password, ...formWithoutCredits } = this.form;
        this.form = formWithoutCredits;
      }

      this.$store
        .dispatch('smtpStore/setSettings', this.form)
        .then((message) => this.successToast(message))
        .catch(({ message }) => this.errorToast(message))
        .finally(() => this.endLoader());
    },
    sendMail() {
      this.$store
        .dispatch('smtpStore/sendTestMessage', {
          from: this.settings.username,
          subject: 'Test Message',
          text: 'Test Message Text',
        })
        .then((message) => this.successToast(message))
        .catch(({ message }) => this.errorToast(message));
    },
    setForm() {
      if (!this.settings) {
        return;
      }

      this.form.username = this.settings.username;
      this.form.password = this.settings.password;
      this.form.host = this.settings.host;
      this.form.port = this.settings.port;
      this.form.is_need_auth = this.settings.is_need_auth;
      this.form.is_need_ssl = this.settings.is_need_ssl;
    },
    resetAuthForm() {
      this.form.username = null;
      this.form.password = null;
    },
  },
};
</script>

<style lang="scss" scoped>
.switch-group {
  margin-bottom: 1.5rem;
}
.smtp-warning {
  width: 50%;
  @media (max-width: 1200px) {
    width: 75%;
  }
  @media (max-width: 576px) {
    width: 100%;
  }
}
</style>
