<template>
  <collapse
    id="collapse_InputVolt"
    :title="$t('pagePowerSup.InputVolt')"
    @opened="onOpened"
  >
    <template #image>
      <img src="@/assets/images/_sila/collapsed/voltage.svg" />
    </template>
    <page-section>
      <!--      <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"
              type="number"
              :min="0"
              :max="245"
            ></b-form-input>
          </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"
              type="number"
              :min="warning"
              :max="250"
            >
            </b-form-input>
          </b-form-group>
        </b-col>
        <b-col xs="12" sm="6" xl="3" class="pt-4">
          <b-button variant="primary" style="height: 35px" @click="saveLimit">
            {{ $t('global.action.save') }}
          </b-button>
        </b-col>
      </b-row>-->
      <chart
        type="voltage-input"
        :time-scale="timeScale"
        :data="filteredItems"
        :colors="colors"
        :warning="warningLimit"
        :critical="criticalLimit"
      ></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 from '@/components/_sila/Mixins/LoadingBarMixin';
import TableFilterMixin from '@/components/_sila/Mixins/TableFilterMixin';
import BVToastMixin from '@/components/_sila/Mixins/BVToastMixin';
import Collapse from '@/components/_sila/Global/Collapse';

import { getGroups, getItems } from '@/utilities/_sila/metricProperties';
import { psuFilter } from '@/utilities/_sila/psuFilter';

export default {
  components: { PageSection, Chart, Collapse },
  mixins: [DataFormatterMixin, LoadingBarMixin, TableFilterMixin, BVToastMixin],
  props: {
    timeScale: {
      type: String,
      default: 'hour',
    },
  },
  data() {
    return {
      warning: null,
      critical: null,
      isBusy: true,
      fields: [
        {
          key: 'name',
          label: this.$t('pagePowerSup.table.nameModule'),
          thStyle: { width: '25%' },
        },
        {
          key: 'current',
          label: this.$t('pagePowerSup.table.currentVolt'),
        },
        {
          key: 'min',
          label: this.$t('pagePowerSup.table.minVolt'),
        },
        {
          key: 'minDate',
          label: this.$t('pagePowerSup.table.minDate'),
        },
        {
          key: 'max',
          label: this.$t('pagePowerSup.table.maxVolt'),
        },
        {
          key: 'maxDate',
          label: this.$t('pagePowerSup.table.maxDate'),
        },
      ],
    };
  },
  computed: {
    groups() {
      return getGroups(this.filteredItems);
    },

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

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

    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;
    },

    filteredItems() {
      return psuFilter(this.allSensors, 'Input');
    },

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

    colors() {
      return this.$randomColor({
        count: this.items?.length,
        hue: 'random',
        luminosity: 'random',
      });
    },
  },
  watch: {
    timeScale() {
      this.loadData();
    },
  },
  created() {
    this.loadData();
  },
  methods: {
    saveLimit() {
      this.startLoader();
      this.$store
        .dispatch('powerSupply/patchLimitsVol', {
          warning: this.warning,
          critical: this.critical,
          groups: this.groups,
        })
        .catch(({ message }) => this.errorToast(message))
        .finally(() => this.endLoader());
    },
    onOpened(state) {
      if (state) {
        this.loadData();
      }
    },
    loadData() {
      let payload = { metricsName: 'psu_voltage', lastHour: false };
      if (this.timeScale === 'hour') {
        payload.lastHour = true;
      }

      this.startLoader();
      this.$store.dispatch('powerSupply/getPsu', payload).finally(() => {
        this.$store.dispatch('powerSupply/getLimitsVol').finally(() => {
          this.warning = this.warningLimit;
          this.critical = this.criticalLimit;
          this.$root.$emit('psu-volt');
          this.endLoader();
          this.isBusy = false;
        });
      });
    },
  },
};
</script>
