<template>
  <page-section :section-title="$t('pageTransfer.syslog.title')">
    <b-row class="mt-4 justify-content-end syslog-warning">
      <b-col xs="12" sm="12">
        <div class="switch-group">
          <label for="statusSwitch">{{
            $t('pageTransfer.syslog.status')
          }}</label>
          <b-form-checkbox
            id="statusSwitch"
            v-model="syslogStatus"
            data-test-id="checkbox-status"
            switch
            :disabled="loading || isNotAdmin"
            @change="onChangeStatusCheckbox($event)"
          >
            <span v-if="syslogStatus">
              {{ $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.syslog.ip')"
          label-for="syslog-ip"
        >
          <b-form-input
            id="syslog-ip"
            v-model="form.Address"
            :state="getValidationState($v.form.Address)"
            :disabled="!syslogStatus || loading || isNotAdmin"
            @input="$v.form.Address.$touch()"
          />
          <b-form-invalid-feedback role="alert">
            <template v-if="!$v.form.Address.required">
              {{ $t('global.form.fieldRequired') }}
            </template>
            <template v-if="!$v.form.Address.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.syslog.port')"
          label-for="syslog-port"
        >
          <b-form-input
            id="syslog-port"
            v-model="form.Port"
            type="number"
            :state="getValidationState($v.form.Port)"
            :disabled="!syslogStatus || loading || isNotAdmin"
            @input="$v.form.Address.$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="4" class="d-flex justify-content-end align-items-start">
        <b-button
          variant="primary"
          :disabled="loading || isNotAdmin"
          @click="saveSyslog"
        >
          {{ $t('global.action.save') }}
        </b-button>
      </b-col>
    </b-row>
  </page-section>
</template>

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

import { helpers, ipAddress, requiredIf } from 'vuelidate/lib/validators';
import VuelidateMixin from '@/components/_sila/Mixins/VuelidateMixin.js';
import { isoPortRegex } from '@/utilities/_sila/regexConstants';

export default {
  name: 'Syslog',
  components: {
    PageSection,
  },
  mixins: [BVToastMixin, LoadingBarMixin, VuelidateMixin],

  data() {
    return {
      loading,
      syslogStatus: false,
      form: {
        Address: null,
        Port: null,
      },
    };
  },
  computed: {
    settings() {
      return this.$store.getters['syslogStore/settings'];
    },
    isNotAdmin() {
      return (
        this.$store.getters['authentication/role'] === 'ReadOnly' ||
        this.$store.getters['authentication/role'] === 'Operator'
      );
    },
  },

  watch: {
    settings() {
      this.setForm();
    },
  },

  created() {
    this.startLoader();
    this.$store.dispatch('syslogStore/getSettings').finally(() => {
      this.setForm();
      this.endLoader();
    });
  },

  validations() {
    return {
      form: {
        Address: {
          required: requiredIf(function () {
            return this.syslogStatus;
          }),
          ipAddress,
        },
        Port: {
          required: requiredIf(function () {
            return this.syslogStatus;
          }),
          pattern: helpers.regex('pattern', isoPortRegex),
        },
      },
    };
  },

  methods: {
    onChangeStatusCheckbox($event) {
      if (!$event) {
        this.resetForm();
      }
    },
    saveSyslog() {
      this.$v.$touch();
      if (this.$v.$invalid) return;

      this.startLoader();
      if (!this.syslogStatus) {
        this.form = {
          Address: '',
          Port: 0,
        };
      }

      this.form.Port = +this.form.Port;
      this.$store
        .dispatch('syslogStore/saveSettings', this.form)
        .then((success) => this.successToast(success))
        .catch(({ message }) => this.errorToast(message))
        .finally(() => this.endLoader());
    },

    setForm() {
      if (!this.settings) {
        return;
      }

      const isOff = !this.settings.Address && this.settings.Port === 0;

      if (isOff) {
        this.syslogStatus = false;
        this.form.Address = null;
        this.form.Port = null;
      } else {
        this.syslogStatus = true;
        this.form.Address = this.settings.Address;
        this.form.Port = this.settings.Port;
      }
    },

    resetForm() {
      this.form.Address = null;
      this.form.Port = null;
    },
  },
};
</script>

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