<template>
  <b-modal ref="realTimeHistoricalModal" modalID="reatime-historical-modal" hide-footer>
    <div class="realtime-historical-wrap">
      <ul class="tabs">
        <li @click="selectTab('realtime')" :class="{'active': (selectedTab === 'realtime')}">Realtime</li>
        <li @click="selectTab('historical')" :class="{'active': (selectedTab === 'historical')}">History</li>
      </ul>
      <div class="dashboard-settings-wrap">
        <section v-if="selectedTab === 'realtime'">
          <b-form>
            <b-form-group label="Last">
              <multiselect v-model="selectedRealtimeGrouping" @select="onSelectRealtimeGrouping" :options="realtimeGroupingData" :select-label="''" :selected-label="''" :deselect-label="''" label="name" track-by="key" :allow-empty="false"></multiselect>
            </b-form-group>
            <b-form-group label="Data aggregation function">
              <multiselect v-model="selectedAggFunction" :options="aggregationFunctions" :select-label="''" :selected-label="''" :deselect-label="''" :allow-empty="false" ></multiselect>
            </b-form-group>
            <b-form-group :label="selectedAggFunction === 'no' ? 'Refresh Rate' : 'Grouping interval'">
              <multiselect v-model="selectedRealtimeInterval" :options="selectedRealtimeGrouping.groupingIntervals" :select-label="''" :selected-label="''" :deselect-label="''" label="name" track-by="key" :allow-empty="false" ></multiselect>
            </b-form-group>
          </b-form>
        </section>
        <section v-if="selectedTab === 'historical'" class="historical-section">
          <b-form>
            <b-form-group label="" class="historical-type">
              <b-form-radio v-model="historicalSettingType" name="historicalSettingType" value="relative">Relative</b-form-radio>
              <b-form-radio v-model="historicalSettingType" name="historicalSettingType" value="absolute">Absolute</b-form-radio>
            </b-form-group>
            <div v-if="historicalSettingType === 'absolute'" class="range-wrap">
              <b-form-group label="From">
                <vc-date-picker v-model="range.start" mode="dateTime">
                  <template v-slot="{ inputValue, inputEvents }">
                    <input
                      :value="inputValue"
                      v-on="inputEvents"
                    />
                  </template>
                </vc-date-picker>
              </b-form-group>
              <b-form-group label="To">
                <vc-date-picker v-model="range.end" mode="dateTime">
                  <template v-slot="{ inputValue, inputEvents }">
                    <input
                      :value="inputValue"
                      v-on="inputEvents"
                    />
                  </template>
                </vc-date-picker>
              </b-form-group>
            </div>
            <b-form-group label="Last" v-if="historicalSettingType === 'relative'">
              <multiselect v-model="selectedHistoricalGrouping" @select="onSelectHistoricalGrouping" :options="historicalGroupingData" :select-label="''" :selected-label="''" :deselect-label="''" label="name" track-by="key" :allow-empty="false"></multiselect>
            </b-form-group>
            <b-form-group label="Data aggregation function">
              <multiselect v-model="selectedAggFunction" :options="aggregationFunctions" :select-label="''" :selected-label="''" :deselect-label="''" :allow-empty="false"></multiselect>
            </b-form-group>
            <b-form-group label="Grouping interval" v-if="selectedAggFunction !== 'no'">
              <multiselect v-model="selectedHistoricalInterval" :options="selectedHistoricalGrouping.groupingIntervals" :select-label="''" :selected-label="''" :deselect-label="''" label="name" track-by="key" :allow-empty="false" ></multiselect>
            </b-form-group>
          </b-form>
        </section>
      </div>
      <div class="mads-footer">
        <b-button variant="outline-primary" @click="onCancel()">Cancel</b-button>
        <b-button variant="primary" @click="onSave()">Save</b-button>
      </div>
    </div>
  </b-modal>
</template>

<script>
import groupingData from './groupingData'

export default {
  props: {
    entityType: {
      type: String,
      default: 'panel'
    },
    dashboardType: {
      type: String
    },
    currentUser: {},
    selectedDashboard: {},
    selectedPanel: {}
  },
  data () {
    return {
      selectedTab: 'realtime',
      realtimeGroupingData: [],
      historicalGroupingData: [],
      selectedRealtimeGrouping: {},
      selectedHistoricalGrouping: {},
      selectedRealtimeInterval: {},
      selectedHistoricalInterval: {},
      aggregationFunctions: ['no', 'min', 'max', 'average', 'sum', 'count'],
      selectedAggFunction: '',
      historicalSettingType: 'relative',
      range: {
        start: null,
        end: null
      }
    }
  },
  methods: {
    setCustomGroupingInterval () {
      let endDate = this.$moment(this.range.end)
      let startDate = this.$moment(this.range.start)

      let diffDays = endDate.diff(startDate, 'days')
      let diffMonths = endDate.diff(startDate, 'months')
      let diffYears = endDate.diff(startDate, 'years')

      if (diffYears >= 1) {
        this.selectedHistoricalGrouping = this.historicalGroupingData[21]
        this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]
      } else if (diffMonths >= 6) {
        this.selectedHistoricalGrouping = this.historicalGroupingData[20]
        this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]
      } else if (diffMonths >= 3) {
        this.selectedHistoricalGrouping = this.historicalGroupingData[19]
        this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]
      } else if (diffDays >= 30) {
        this.selectedHistoricalGrouping = this.historicalGroupingData[18]
        this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]
      } else if (diffDays >= 7) {
        this.selectedHistoricalGrouping = this.historicalGroupingData[17]
        this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]
      } else if (diffDays >= 1) {
        this.selectedHistoricalGrouping = this.historicalGroupingData[16]
        this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]
      }
    },
    open (params = {}) {
      let filterMetadata = {}
      if (this.entityType === 'widget' && !this.$_.isEmpty(params)) {
        filterMetadata = params
      } else {
        if (this.dashboardType === 'exportedDashboard') {
          let exportedDashboardKey = 'exported_dashboard_' + this.selectedDashboard.uuid + '_filter_metadata'
          let exportedDashboardFilterMetadata = localStorage.getItem(exportedDashboardKey)
          filterMetadata = exportedDashboardFilterMetadata ? JSON.parse(exportedDashboardFilterMetadata) : this.selectedPanel.filter_metadata
        } else {
          filterMetadata = this.selectedPanel.filter_metadata
        }
      }

      let lastKey = filterMetadata.last
      let intervalKey = filterMetadata.group_interval + '_' + filterMetadata.group_interval_type
      let startDate = filterMetadata.from_date
      let endDate = filterMetadata.to_date

      if (filterMetadata.type === 'realtime') {
        this.selectedRealtimeGrouping = this.$_.find(this.realtimeGroupingData, (grouping) => { return grouping.key === lastKey })
        this.selectedRealtimeInterval = this.$_.find(this.selectedRealtimeGrouping.groupingIntervals, (interval) => { return interval.key === intervalKey })
      } else {
        if (lastKey === 'custom') {
          this.historicalSettingType = 'absolute'

          this.range = this.$_.merge({}, {
            start: this.$moment(startDate).toDate(),
            end: this.$moment(endDate).toDate()
          })

          this.setCustomGroupingInterval()
        } else {
          this.selectedHistoricalGrouping = this.$_.find(this.historicalGroupingData, (grouping) => { return grouping.key === lastKey })
          this.selectedHistoricalInterval = this.$_.find(this.selectedHistoricalGrouping.groupingIntervals, (interval) => { return interval.key === intervalKey })
        }
      }

      this.selectedTab = filterMetadata.type
      this.selectedAggFunction = filterMetadata.aggregate_func

      this.$refs.realTimeHistoricalModal.show()
    },
    onCancel () {
      this.$refs.realTimeHistoricalModal.hide()
    },
    onSave () {
      this.$refs.realTimeHistoricalModal.hide()

      let selectedGrouping = (this.selectedTab === 'realtime') ? this.selectedRealtimeGrouping : this.selectedHistoricalGrouping
      let selectedInterval = (this.selectedTab === 'realtime') ? this.selectedRealtimeInterval : this.selectedHistoricalInterval

      let todayDate = this.$moment()
      let endDate = null
      let startDate = null

      if ((this.selectedTab === 'historical') && (this.historicalSettingType === 'absolute')) {
        endDate = this.$moment(this.range.end).format('x')
        startDate = this.$moment(this.range.start).format('x')
      } else {
        endDate = todayDate.format('x')
        startDate = todayDate.subtract(selectedGrouping.value, selectedGrouping.type).format('x')
      }

      let params = {
        filter_metadata: {
          aggregate_func: this.selectedAggFunction,
          from_date: startDate,
          to_date: endDate,
          group_interval: selectedInterval.value,
          group_interval_type: (selectedInterval.type).slice(0, -1),
          type: this.selectedTab,
          last: ((this.selectedTab === 'historical') && (this.historicalSettingType === 'absolute')) ? 'custom' : selectedGrouping.key
        }
      }

      if (this.entityType === 'panel') {
        if (this.dashboardType === 'exportedDashboard') {
          // Save this settings to local storage, since it will be specific to the user viewing the exported dashboard
          let exportedDashboardKey = 'exported_dashboard_' + this.selectedDashboard.uuid + '_filter_metadata'
          localStorage.setItem(exportedDashboardKey, JSON.stringify(params.filter_metadata))
        }
        this.$emit('save-panel-realtime-historical-settings', params)
      } else {
        this.$emit('set-realtime-historical-settings', params.filter_metadata)
      }
    },
    selectTab (tab) {
      this.selectedTab = tab
    },
    onSelectRealtimeGrouping (grouping) {
      this.selectedRealtimeInterval = grouping.groupingIntervals[0]
    },
    onSelectHistoricalGrouping (grouping) {
      this.selectedHistoricalInterval = grouping.groupingIntervals[0]
    },
    initData () {
      this.realtimeGroupingData = this.$_.take(groupingData, 13)
      this.selectedRealtimeGrouping = this.realtimeGroupingData[12]
      this.selectedRealtimeInterval = this.selectedRealtimeGrouping.groupingIntervals[0]

      this.historicalGroupingData = groupingData
      this.selectedHistoricalGrouping = this.historicalGroupingData[18]
      this.selectedHistoricalInterval = this.selectedHistoricalGrouping.groupingIntervals[0]

      this.selectedAggFunction = this.aggregationFunctions[2]
    }
  },
  mounted () {
    this.initData()
  }
}
</script>

<style lang="scss" scoped>
  .realtime-historical-wrap {
    padding: 30px 0;
    width: 100%;
    .tabs {
      list-style: none;
      display: flex;
      font-size: 18px;
      padding: 0;
      li {
        width: 50%;
        cursor: pointer;
        text-align: center;
        border-bottom: 1px solid #e2e2e2;
        &.active {
          border-bottom: 2px solid #305680;
        }
      }
    }
    .dashboard-settings-wrap {
      padding: 20px 30px;
      height: 420px;
    }
    .mads-footer {
      text-align: right;
      padding: 0px 30px;
      padding: 0 30px;
    }
    .custom-date-picker {
      svg {
        width: 21px;
        height: 21px;
      }
      .border {
        border: 1px solid #e8e8e8 !important;
        border-radius: 5px !important;
        min-height: 40px;
        width: 44%;
      }
    }
  }
</style>

<style lang="scss">
  .historical-section {
    .historical-type > div {
      display: flex;
      .custom-radio {
        flex-grow: 1;
        .custom-control-input {
          margin-top: 2px;
        }
        .custom-control-label {
          font-size: 18px;
          color: #212121;
        }
      }
    }
    .range-wrap {
      display: flex;
      justify-content: space-between;
      .form-group {
        width: 50%;
        input {
          width: calc(100% - 5px);
        }
      }
    }
  }
</style>
