<template>
  <div :class="{ disabledDiv: loading }">
    <b-col class="d-flex flex-nowrap align-items-center page-divider">
      <img src="@/assets/images/_sila/collapsed/temperature.svg" />
      {{ $t('pageMotherboard.temperature') }}
    </b-col>

    <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('pageMotherboard.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" 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="motherboard"
      :time-scale="timeScale"
      :colors="colors"
      :data="filteredSensors"
      :warning="warningLimit"
      :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>
  </div>
</template>
<script>
import Chart from '@/components/_sila/Global/Chart';

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 { getItems, getGroups } from '@/utilities/_sila/metricProperties';
import { between, required } from 'vuelidate/lib/validators';

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

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

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

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

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

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

    maxLimit() {
      return this.limits.find((limit) => {
        return limit?.MaxReadingRangeTemp;
      })?.MaxReadingRangeTemp;
    },

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

    filteredSensors() {
      return this.getFilteredTableData(this.allSensors, this.activeFilters);
    },

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

  watch: {
    limits() {
      if (this.limits && this.limits.length > 0) {
        this.warning = this.warningLimit;
      }
    },

    timeScale() {
      this.loadData();
    },
  },

  created() {
    this.loadData();
  },

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

      this.startLoader();
      this.$store
        .dispatch('motherboard/patchLimits', {
          warning: this.warning,
          groups: this.groups,
        })
        .catch(({ message }) => this.errorToast(message))
        .finally(() => this.endLoader());
    },

    loadData() {
      let payload = { lastHour: false };
      if (this.timeScale === 'hour') {
        payload = { lastHour: true };
      }

      this.start();
      this.$store
        .dispatch('motherboard/getMotherboardDynamic', payload)
        .finally(() => {
          this.$store.dispatch('motherboard/getLimits').finally(() => {
            this.warning = this.warningLimit;
            this.end();
          });
        });
    },

    start() {
      this.startLoader();
      this.isBusy = true;
      this.$root.$emit('motherboard', true);
    },

    end() {
      this.endLoader();
      this.isBusy = false;
      this.$root.$emit('motherboard', false);
    },
  },
};
</script>
