<template>
  <div class="economy">
    <h3 class="text-center mt-2">Economy</h3>
    <div class="flexbreak"></div>
    <div id="economy-graph"></div>
  </div>
</template>

<script>

import {GetPlayerValue} from "@/utils";
import {useStore} from "vuex";
import {onBeforeMount, onMounted, onUnmounted, reactive, ref, watch} from "vue";

import * as echarts from 'echarts/core';
import {
  GridComponent,
  MarkAreaComponent,
  TitleComponent,
  TooltipComponent,
  VisualMapComponent
} from 'echarts/components';
import {LineChart} from 'echarts/charts';
import {UniversalTransition} from 'echarts/features';
import {CanvasRenderer} from 'echarts/renderers';

export default {
  name: "EqValueGraph",
  setup() {
    const store = useStore()

    let myChart1, max_rounds
    let valueList = []
    let dataList = []
    const width = ref(window.innerWidth >= 800 && window.innerWidth <= 1200 ? window.innerWidth : window.innerWidth < 800 ? 800 : 1200)
    const height = ref(width.value * 1 / 3)

    const data = reactive({
      rounds: {},
      team: [],
      eq_team_1: [],
      eq_team_2: [],
      eq_team_player_1: [],
      eq_team_player_2: [],
    })

    const getTeamPlayer = (stats, team) => {
      let arr = []
      for (let i = (team - 1) * 5; i < team * 5; i++) {
        arr.push(stats[i].player.steamid64)
      }

      return arr
    }

    const parseObject = async () => {
      data.rounds = await GetPlayerValue(store, store.state.matchDetails.match_id)
      if (data.rounds === null)
        data.rounds = {}

      for (const round in data.rounds) {
        for (const player in data.rounds[round]) {
          for (let p in data.team[0]) {
            if (data.team[0][p] === player) {
              data.eq_team_player_1.push({
                round: round,
                player: player,
                eq: (data.rounds[round][player][0] + data.rounds[round][player][2])
              })
            }
          }
          for (let p in data.team[1]) {
            if (data.team[1][p] === player) {
              data.eq_team_player_2.push({
                round: round,
                player: player,
                eq: (data.rounds[round][player][0] + data.rounds[round][player][2])
              })
            }
          }
        }
      }
    }

    const sumArr = (arr) => {
      return arr.reduce((acc, current) => ({
        ...acc,
        [current.round]: (acc[current.round] || 0) + current.eq
      }), {})
    }

    const BuildGraphData = (team_1, team_2, max_rounds) => {
      let newArr = []
      const half_point = max_rounds / 2 - 1
      for (let round in team_1) {
        if (round <= half_point) {
          newArr.push(team_1[round] - team_2[round])
        } else
          newArr.push(team_2[round] - team_1[round])
      }
      return newArr
    }

    const optionGen = (dataList, valueList) => {
      return {
        // Make gradient line here
        visualMap: [
          {
            show: false,
            type: 'continuous',
            seriesIndex: 0,
            color: ['#3a6e99', '#c3a235'],
          },
        ],
        tooltip: {
          trigger: 'axis',
          formatter: 'Round <b>{b0}</b><br />{a0} <b>{c0}</b>',
        },
        xAxis: [
          {
            type: 'category',
            data: dataList,
          }
        ],
        yAxis: [
          {},
        ],
        grid: [
          {
            bottom: '10%'
          },
          {
            top: '0%'
          },
          {
            right: '0%'
          },
          {
            left: '0%'
          }
        ],
        series: [
          {
            name: 'Net-Worth',
            type: 'line',
            lineStyle: {
              width: 4
            },
            showSymbol: false,
            data: valueList,
            markArea: {
              data: [
                [
                  {
                    name: 'Half-Point',
                    xAxis: max_rounds / 2 - 1,
                    label: {
                      color: 'white'
                    },
                  },
                  {
                    xAxis: max_rounds / 2
                  }
                ]
              ],
              itemStyle: {
                color: 'rgba(200,200,200, 0.3)'
              }
            }
          },
        ],
      }
    }

    const disposeCharts = () => {
      if (myChart1 != null && myChart1 !== '' && myChart1 !== undefined) {
        myChart1.dispose()
      }
    }

    const buildCharts = () => {
      disposeCharts()

      myChart1 = echarts.init(document.getElementById('economy-graph'), {}, {
        width: width.value,
        height: height.value
      })
      myChart1.setOption(optionGen(dataList, valueList))
    }

    onBeforeMount(() => {
      max_rounds = store.state.matchDetails.max_rounds ? store.state.matchDetails.max_rounds : 30
    })

    onMounted(() => {
      if (store.state.matchDetails.stats) {
        echarts.use([
          TitleComponent,
          TooltipComponent,
          GridComponent,
          VisualMapComponent,
          LineChart,
          CanvasRenderer,
          UniversalTransition,
          MarkAreaComponent
        ]);

        data.team.push(getTeamPlayer(store.state.matchDetails.stats, 1))
        data.team.push(getTeamPlayer(store.state.matchDetails.stats, 2))

        parseObject()
      }
    })

    onUnmounted(() => {
      disposeCharts()
    })

    watch(() => data.rounds, () => {
      data.eq_team_1 = sumArr(data.eq_team_player_1)
      data.eq_team_2 = sumArr(data.eq_team_player_2)

      valueList = BuildGraphData(data.eq_team_1, data.eq_team_2, max_rounds)

      dataList = Array.from(Array(valueList.length + 1).keys())
      dataList.shift()

      buildCharts()
    })

    window.onresize = () => {
      if (window.innerWidth > 1200) {
        width.value = 1200
      }
      if (window.innerWidth <= 1200 && window.innerWidth >= 800) {
        width.value = window.innerWidth - 20
      }
      if (window.innerWidth < 800) {
        width.value = 800
      }

      height.value = width.value * 1 / 3
      buildCharts()
    }
  }
}
</script>

<style lang="scss" scoped>
.economy {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  margin: 0 auto 3rem;

  h3 {
    margin-bottom: -1rem;
    z-index: 2;
  }
}

@media (max-width: 1200px) {
  h3 {
    margin-left: 2rem;
  }
}

@media (max-width: 800px) and (min-width: 1199px) {
  #economy-graph {
    overflow: scroll;
  }
}
</style>
