<template>
  <collapse
    id="collapse_psuTempp"
    :class="{ disabledDiv: loading && opened }"
    :title="$t('pagePowerSup.temperature')"
    :opened="true"
    @opened="onOpened"
  >
    <template #image>
      <img src="@/assets/images/_sila/collapsed/temperature.svg" />
    </template>
    <page-section>
      <b-form novalidate>
        <b-row class="align-items-end limit-container">
          <b-col xs="12" sm="6" xl="3" class="pt-4">
            <b-form-group :label="$t('pagePowerSup.labels.warning')">
              <b-form-input
                v-model.number="warning"
                :disabled="$store.getters['authentication/role'] === 'ReadOnly'"
                type="number"
                :state="getValidationState($v.warning)"
                @blur="$v.warning.$touch()"
              >
              </b-form-input>
              <b-form-invalid-feedback class="absolute" role="alert">
                <div v-if="!$v.warning.between">
                  {{ $t('global.form.invalidValue') }}
                </div>
                <div v-if="!$v.warning.required">
                  {{ $t('global.form.fieldRequired') }}
                </div>
              </b-form-invalid-feedback>
            </b-form-group>
          </b-col>
          <b-col xs="12" sm="6" xl="3" class="pt-4">
            <b-form-group :label="$t('pagePowerSup.labels.critical')">
              <b-form-input
                v-model.number="critical"
                :disabled="$store.getters['authentication/role'] === 'ReadOnly'"
                type="number"
                :state="getValidationState($v.critical)"
                @blur="$v.critical.$touch()"
              >
              </b-form-input>
              <b-form-invalid-feedback class="absolute" role="alert">
                <div v-if="!$v.critical.between">
                  {{ $t('global.form.invalidValue') }}
                </div>
                <div v-if="!$v.critical.required">
                  {{ $t('global.form.fieldRequired') }}
                </div>
              </b-form-invalid-feedback>
            </b-form-group>
          </b-col>
          <b-col xs="12" sm="6" xl="3" class="pt-4">
            <b-button
              variant="primary"
              style="height: 35px"
              :disabled="
                loading || $store.getters['authentication/role'] === 'ReadOnly'
              "
              @click="saveLimit"
            >
              {{ $t('global.action.save') }}
            </b-button>
          </b-col>
        </b-row>
      </b-form>
      <chart
        type="processors"
        :time-scale="timeScale"
        :data="allSensors"
        :colors="colors"
        :warning="warningLimit"
        :critical="criticalLimit"
        :max="maxLimit"
      ></chart>
      <b-table
        responsive="md"
        show-empty
        table-variant="accessory"
        hover
        :items="items"
        :fields="fields"
        :empty-text="$t('global.table.emptyMessage')"
        :busy="isBusy"
      >
        <template #cell(name)="{ value, index }">
          <div
            class="item-color"
            :style="`background-color: ${colors[index]}`"
          ></div>
          {{ value }}
        </template>
        <template #cell(minDate)="{ value }">
          <span style="color: rgb(12, 28, 41)">
            {{ value.time }}
          </span>
          <span>
            {{ value.date }}
          </span>
        </template>
        <template #cell(maxDate)="{ value }">
          <span style="color: rgb(12, 28, 41)">
            {{ value.time }}
          </span>
          <span>
            {{ value.date }}
          </span>
        </template>
      </b-table>
    </page-section>
  </collapse>
</template>
<script>
import Chart from '@/components/_sila/Global/Chart';
import PageSection from '@/components/Global/PageSection';

import DataFormatterMixin from '@/components/_sila/Mixins/DataFormatterMixin';
import LoadingBarMixin, {
  loading,
} from '@/components/_sila/Mixins/LoadingBarMixin';
import TableFilterMixin from '@/components/_sila/Mixins/TableFilterMixin';
import BVToastMixin from '@/components/_sila/Mixins/BVToastMixin';
import VuelidateMixin from '@/components/_sila/Mixins/VuelidateMixin.js';
import Collapse from '@/components/_sila/Global/Collapse';

import { getGroups, getItems } from '@/utilities/_sila/metricProperties';
import { between, required } from 'vuelidate/lib/validators';

export default {
  components: { PageSection, Chart, Collapse },
  mixins: [
    DataFormatterMixin,
    TableFilterMixin,
    LoadingBarMixin,
    BVToastMixin,
    VuelidateMixin,
  ],
  props: {
    timeScale: {
      type: String,
      default: 'hour',
    },
  },
  data() {
    return {
      loading,
      warning: null,
      critical: null,
      isBusy: true,
      opened: false,
      fields: [
        {
          key: 'name',
          label: this.$t('pagePowerSup.table.nameModule'),
          thStyle: { width: '25%' },
        },
        {
          key: 'current',
          label: this.$t('pagePowerSup.table.currentTemperature'),
        },
        {
          key: 'middle',
          label: this.$t('pagePowerSup.table.middleTemperature'),
        },
        {
          key: 'min',
          label: this.$t('pagePowerSup.table.minTemperature'),
        },
        {
          key: 'minDate',
          label: this.$t('pagePowerSup.table.minDate'),
        },
        {
          key: 'max',
          label: this.$t('pagePowerSup.table.maxTemperature'),
        },
        {
          key: 'maxDate',
          label: this.$t('pagePowerSup.table.maxDate'),
        },
      ],
    };
  },

  validations() {
    return {
      warning: {
        required,
        between: between(1, this.critical),
      },
      critical: {
        required,
        between: between(this.warning, this.maxLimit),
      },
    };
  },

  computed: {
    groups() {
      return getGroups(this.allSensors);
    },

    items() {
      return getItems(this.allSensors);
    },

    limits() {
      return this.$store.getters['powerSupply/limitsTemp'];
    },

    warningLimit() {
      return this.limits.find((limit) => {
        return (
          limit?.UpperThresholdNonCritical &&
          this.groups.includes(limit.MemberId)
        );
      })?.UpperThresholdNonCritical;
    },

    criticalLimit() {
      return this.limits.find((limit) => {
        return (
          limit?.UpperThresholdCritical && this.groups.includes(limit.MemberId)
        );
      })?.UpperThresholdCritical;
    },

    maxLimit() {
      return 100;
    },

    allSensors() {
      return this.timeScale === 'hour'
        ? this.$store.getters['powerSupply/psuTempLastHour']
        : this.$store.getters['powerSupply/psuTemp'];
    },

    colors() {
      return this.$randomColor({
        count: this.items?.length,
        hue: 'random',
        luminosity: 'random',
      });
    },
  },
  watch: {
    timeScale() {
      if (!this.opened) {
        return;
      }

      this.loadData();
    },
  },

  methods: {
    saveLimit() {
      this.$v.$touch();
      if (this.$v.$invalid) return;

      this.startLoader();
      this.$store
        .dispatch('powerSupply/patchLimitsTemp', {
          warning: this.warning,
          critical: this.critical,
          groups: this.groups,
        })
        .catch(({ message }) => this.errorToast(message))
        .finally(() => this.endLoader());
    },
    onOpened(state) {
      if (state) {
        this.loadData();
      }
      this.opened = state;
    },
    loadData() {
      let payload = { metricsName: 'psu_temp', lastHour: false };
      if (this.timeScale === 'hour') {
        payload.lastHour = true;
      }
      this.$root.$emit('psu-temp', true);
      this.startLoader();
      this.$store.dispatch('powerSupply/getPsu', payload).finally(() => {
        this.$store.dispatch('powerSupply/getLimitsTemp').finally(() => {
          this.warning = this.warningLimit;
          this.critical = this.criticalLimit;
          this.$root.$emit('psu-temp', false);
          this.endLoader();
          this.isBusy = false;
        });
      });
    },
  },
};
</script>
