<script>
import dateFormat from 'dateformat';
import { mapState, mapGetters, mapActions } from 'vuex';
import { GlChart } from '@gitlab/ui/dist/charts';
import { __ } from '~/locale';
import ChartTooltip from './vulnerability_chart_tooltip.vue';
import ChartButtons from './vulnerability_chart_buttons.vue';
import { DAY_IN_MS, DAYS } from '../store/modules/vulnerabilities/constants';
import { SEVERITY_LEVELS } from '../store/constants';
import ResizableChartContainer from '~/vue_shared/components/resizable_chart/resizable_chart_container.vue';

export default {
  name: 'VulnerabilityChart',
  components: {
    GlChart,
    ChartTooltip,
    ChartButtons,
    ResizableChartContainer,
  },
  DAYS,
  data: () => ({
    tooltipTitle: '',
    tooltipEntries: [],
    lines: [
      {
        name: SEVERITY_LEVELS.critical,
        color: '#C0341D',
      },
      {
        name: SEVERITY_LEVELS.high,
        color: '#DE7E00',
      },
      {
        name: SEVERITY_LEVELS.medium,
        color: '#6E49CB',
      },
      {
        name: SEVERITY_LEVELS.low,
        color: '#4F4F4F',
      },
      {
        name: __('Total'),
        color: '#1F78D1',
      },
    ],
  }),
  computed: {
    ...mapState('vulnerabilities', [
      'vulnerabilitiesHistory',
      'vulnerabilitiesHistoryDayRange',
      'vulnerabilitiesHistoryShowSplitLine',
      'vulnerabilitiesHistoryMaxDayInterval',
    ]),
    ...mapGetters('vulnerabilities', ['getFilteredVulnerabilitiesHistory']),
    series() {
      return this.lines.map(line => {
        const { name, color } = line;
        const data = this.getFilteredVulnerabilitiesHistory(name);

        return {
          borderWidth: 2,
          color,
          data,
          name,
          symbol: 'circle',
          symbolSize: 6,
          type: 'line',
        };
      });
    },
    options() {
      return {
        grid: {
          bottom: 85,
          left: 75,
          right: 15,
          top: 10,
        },
        tooltip: {
          backgroundColor: '#fff',
          borderColor: 'rgba(0, 0, 0, 0.1)',
          borderWidth: 1,
          confine: true,
          formatter: this.renderTooltip,
          padding: 0,
          textStyle: {
            color: '#4F4F4F',
          },
          trigger: 'axis',
        },
        xAxis: {
          axisLabel: {
            color: '#707070',
            formatter: date => dateFormat(date, 'd mmm'),
            margin: 8,
            rotate: 45,
          },
          axisLine: {
            lineStyle: {
              color: '#dedede',
              width: 2,
            },
          },
          splitLine: {
            show: this.vulnerabilitiesHistoryShowSplitLine,
          },
          axisTick: {
            show: false,
          },
          maxInterval: DAY_IN_MS * this.vulnerabilitiesHistoryMaxDayInterval,
          min: Date.now() - DAY_IN_MS * this.vulnerabilitiesHistoryDayRange,
          name: 'Date',
          nameGap: 50,
          nameLocation: 'center',
          nameTextStyle: {
            color: '#2e2e2e',
            fontWeight: 'bold',
          },
          splitNumber: 12,
          type: 'time',
        },
        yAxis: {
          axisLabel: {
            color: '#707070',
          },
          axisLine: {
            lineStyle: {
              color: '#dedede',
              width: 2,
            },
          },
          axisTick: {
            show: false,
          },
          boundaryGap: [0, '5%'],
          name: 'Vulnerabilities',
          nameGap: 42,
          nameLocation: 'center',
          nameRotation: 90,
          nameTextStyle: {
            color: '#2e2e2e',
            fontWeight: 'bold',
          },
          minInterval: 1,
          type: 'value',
        },
        legend: {
          bottom: 0,
          icon: 'path://M0,0H120V40H0Z',
          itemGap: 15,
          left: 70,
          textStyle: {
            color: '#4F4F4F',
            fontWeight: 'bold',
          },
          type: 'scroll',
        },
        series: this.series,
      };
    },
    days() {
      const { $options } = this;
      return [$options.DAYS.THIRTY, $options.DAYS.SIXTY, $options.DAYS.NINETY];
    },
  },
  methods: {
    ...mapActions('vulnerabilities', ['setVulnerabilitiesHistoryDayRange']),
    renderTooltip(params, ticket, callback) {
      this.tooltipTitle = dateFormat(params[0].axisValue, 'd mmmm');
      this.tooltipEntries = params;
      this.$nextTick(() => callback(ticket, this.$refs.tooltip.$el.innerHTML));
      return ' ';
    },
  },
};
</script>

<template>
  <div>
    <div class="d-flex justify-content-between">
      <h4 class="my-4">{{ __('Vulnerability Chart') }}</h4>

      <div class="align-self-center">
        <chart-buttons
          :days="days"
          :active-day="vulnerabilitiesHistoryDayRange"
          @click="setVulnerabilitiesHistoryDayRange"
        />
      </div>
    </div>

    <div class="vulnerabilities-chart">
      <div class="vulnerabilities-chart-wrapper">
        <resizable-chart-container>
          <gl-chart
            slot-scope="{ width, height }"
            :options="options"
            :width="width"
            :height="height"
            :disable-theme="true"
          />
        </resizable-chart-container>
        <chart-tooltip
          v-show="false"
          ref="tooltip"
          :title="tooltipTitle"
          :entries="tooltipEntries"
        />
      </div>
    </div>
  </div>
</template>
