<template>
  <div class="hitgroup pt-2">
    <div class="select-group mb-4">
      <select v-if="store.state.playersArr" v-model="data.selectPlayer" class="form-select">
        <option value="All">All</option>
        <option value="Team 1">Team 1</option>
        <option value="Team 2">Team 2</option>
        <option disabled>───────────────────────────</option>
        <option v-for="(value, index) in props.stats" :key="index"
                :value="Object.keys(value).toString() === store.state.playersArr[index].player.steamid64 ? store.state.playersArr[index].player : ''">
          {{
            Object.keys(value).toString() === store.state.playersArr[index].player.steamid64 ? store.state.playersArr[index].player.name : ''
          }}
        </option>
      </select>

      <select v-if="data.selectPlayer !== ''" :key="data.selectPlayer" v-model="data.selectWeapon" class="form-select">
        <option class="select-hr" value="All">All</option>
        <option disabled>───────────────────────────</option>
        <option v-for="(value, index) in processPlayerWeapon()" :key="index" :value="value">
          {{ Object.values(value).toString().charAt(0).toUpperCase() + Object.values(value).toString().slice(1) }}
        </option>
      </select>
    </div>

    <div id="hitgroup-puppet"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts/core';
import {GeoComponent, TooltipComponent, VisualMapComponent} from 'echarts/components';
import {MapChart} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';
import {onMounted, onUnmounted, reactive, ref, watch} from "vue";
import {useStore} from "vuex";

import $ from 'jquery'

export default {
  name: "HitgroupPuppet.vue",
  props: {
    equipment_map: {
      type: Object,
      required: true,
    },
    stats: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    const store = useStore()

    const data = reactive({
      selectPlayer: 'All',
      selectWeapon: 'All',
      eq_map: []
    })

    let myChart1

    const getWindowWidth = () => {
      const windowWidth = window.innerWidth
      if (windowWidth <= 750)
        return windowWidth
      else
        return 650
    }

    const setHeight = () => {
      const windowWidth = getWindowWidth()
      if (windowWidth >= 751)
        return windowWidth * 3 / 7.5
      else if (windowWidth >= 501 && windowWidth <= 750)
        return windowWidth * 3 / 6.5
      else
        return windowWidth * 3 / 5.5
    }

    const width = ref(getWindowWidth())
    const height = ref(setHeight())

    const processPlayerWeapon = () => {
      let arr = []
      if (data.selectPlayer === 'All') {
        props.stats.forEach(player => {
          Object.values(player).forEach(enemies => {
            Object.values(enemies).forEach(weapons => {
              Object.values(weapons).forEach(weapon => {
                arr.push(weapon[0])
              })
            })
          })
        })
      } else if (data.selectPlayer === 'Team 1') {
        props.stats.forEach(player => {
          store.state.playersArr.forEach(p => {
            if (p.player.steamid64 === Object.keys(player).toString() && p.team_id === 1)
              Object.values(player).forEach(enemies => {
                Object.values(enemies).forEach(weapons => {
                  Object.values(weapons).forEach(weapon => {
                    arr.push(weapon[0])
                  })
                })
              })
          })
        })
      } else if (data.selectPlayer === 'Team 2') {
        props.stats.forEach(player => {
          store.state.playersArr.forEach(p => {
            if (p.player.steamid64 === Object.keys(player).toString() && p.team_id === 2)
              Object.values(player).forEach(enemies => {
                Object.values(enemies).forEach(weapons => {
                  Object.values(weapons).forEach(weapon => {
                    arr.push(weapon[0])
                  })
                })
              })
          })
        })
      } else {
        props.stats.forEach(player => {
          if (Object.keys(player).toString() === data.selectPlayer.steamid64) {
            Object.values(player).forEach(enemies => {
              Object.values(enemies).forEach(weapons => {
                Object.values(weapons).forEach(weapon => {
                  arr.push(weapon[0])
                })
              })
            })
          }
        })
      }

      const unique = arr.filter((a, b) => arr.indexOf(a) === b && a < 500)

      let arr2 = []

      unique.forEach(w => {
        for (let weapon in props.equipment_map) {
          if (parseInt(w) === parseInt(weapon)) {
            let obj = {}
            obj[w] = props.equipment_map[weapon]
            arr2.push(obj)
          }
        }
      })

      return arr2
    }

    const processDmg = () => {
      let arr = []
      if (data.selectPlayer && data.selectWeapon) {
        switch (data.selectPlayer) {
          case "All":
            props.stats.forEach(player => {
              Object.values(player).forEach(enemies => {
                Object.values(enemies).forEach(weapons => {
                  Object.values(weapons).forEach(weapon => {
                    // 0: weapon
                    // 1: hitgroup
                    // 2: dmg
                    if (weapon) {
                      if (Object.values(weapon)[0] === parseInt(Object.keys(data.selectWeapon).toString())) {
                        let obj = {}
                        obj[weapon[1]] = weapon[2]
                        arr.push(obj)
                      } else if (data.selectWeapon === 'All') {
                        let obj = {}
                        obj[weapon[1]] = weapon[2]
                        arr.push(obj)
                      }
                    }
                  })
                })
              })
            })
            break;

          case "Team 1":
            props.stats.forEach(player => {
              store.state.playersArr.forEach(p => {
                if (p.player.steamid64 === Object.keys(player).toString() && p.team_id === 1)
                  Object.values(player).forEach(enemies => {
                    Object.values(enemies).forEach(weapons => {
                      Object.values(weapons).forEach(weapon => {
                        // 0: weapon
                        // 1: hitgroup
                        // 2: dmg
                        if (weapon) {
                          if (Object.values(weapon)[0] === parseInt(Object.keys(data.selectWeapon).toString())) {
                            let obj = {}
                            obj[weapon[1]] = weapon[2]
                            arr.push(obj)
                          } else if (data.selectWeapon === 'All') {
                            let obj = {}
                            obj[weapon[1]] = weapon[2]
                            arr.push(obj)
                          }
                        }
                      })
                    })
                  })
              })
            })
            break;

          case "Team 2":
            props.stats.forEach(player => {
              store.state.playersArr.forEach(p => {
                if (p.player.steamid64 === Object.keys(player).toString() && p.team_id === 2)
                  Object.values(player).forEach(enemies => {
                    Object.values(enemies).forEach(weapons => {
                      Object.values(weapons).forEach(weapon => {
                        // 0: weapon
                        // 1: hitgroup
                        // 2: dmg
                        if (weapon) {
                          if (Object.values(weapon)[0] === parseInt(Object.keys(data.selectWeapon).toString())) {
                            let obj = {}
                            obj[weapon[1]] = weapon[2]
                            arr.push(obj)
                          } else if (data.selectWeapon === 'All') {
                            let obj = {}
                            obj[weapon[1]] = weapon[2]
                            arr.push(obj)
                          }
                        }
                      })
                    })
                  })
              })
            })
            break;

          default:
            props.stats.forEach(player => {
              if (Object.keys(player).toString() === data.selectPlayer.steamid64) {
                Object.values(player).forEach(enemies => {
                  Object.values(enemies).forEach(weapons => {
                    Object.values(weapons).forEach(weapon => {
                      // 0: weapon
                      // 1: hitgroup
                      // 2: dmg
                      if (weapon) {
                        if (Object.values(weapon)[0] === parseInt(Object.keys(data.selectWeapon).toString())) {
                          let obj = {}
                          obj[weapon[1]] = weapon[2]
                          arr.push(obj)
                        } else if (data.selectWeapon === 'All') {
                          let obj = {}
                          obj[weapon[1]] = weapon[2]
                          arr.push(obj)
                        }
                      }
                    })
                  })
                })
              }
            })
            break;
        }
      } else {
        arr = []
      }
      buildCharts(sumDmgArr(arr))
    }

    const sumDmgArr = (arr) => {
      let holder = {};

      arr.forEach(function (d) {
        // eslint-disable-next-line no-prototype-builtins
        if (holder.hasOwnProperty(parseInt(Object.keys(d).toString()))) {
          holder[parseInt(Object.keys(d).toString())] = holder[parseInt(Object.keys(d).toString())] + parseInt(Object.values(d).toString());
        } else {
          holder[parseInt(Object.keys(d).toString())] = parseInt(Object.values(d).toString());
        }
      });

      let arr2 = [];

      for (let i = 1; i < 8; i++) {
        if (holder[i] !== undefined) {
          arr2.push(holder[i])
        } else {
          arr2.push(0)
        }
      }

      return arr2
    }

    const getMax = (arr) => {
      let max = 0
      for (let i = 0; i < 7; i++) {
        if (arr[i] > max)
          max = arr[i]
      }
      return max
    }

    const optionGen = (arr = []) => {
      return {
        tooltip: {},
        visualMap: {
          left: 'center',
          bottom: '5%',
          textStyle: {
            color: 'white',
          },
          min: 0,
          max: getMax(arr) || 100,
          orient: 'horizontal',
          realtime: true,
          calculable: true,
          inRange: {
            color: ['#00ff00', '#db6e00', '#cf0000']
          }
        },
        series: [
          {
            name: 'Hitgroup',
            type: 'map',
            map: 'hitgroup-puppet',
            top: '0%',
            emphasis: {
              label: {
                show: false
              }
            },
            selectedMode: false,
            data: [
              {name: 'Head', value: arr[0] || 0},
              {name: 'Chest', value: arr[1] || 0},
              {name: 'Stomach', value: arr[2] || 0},
              {name: 'Left Arm', value: arr[3] || 0},
              {name: 'Right Arm', value: arr[4] || 0},
              {name: 'Left Foot', value: arr[5] || 0},
              {name: 'Right Foot', value: arr[6] || 0}
            ]
          }
        ]
      }
    }

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

    const buildCharts = (arr) => {
      disposeCharts()

      myChart1 = echarts.init(document.getElementById('hitgroup-puppet'), {}, {width: 300, height: 500})

      const url = require('@/assets/images/icons/hitgroup-puppet.svg')
      $.get(url, function (svg) {
        echarts.registerMap('hitgroup-puppet', {svg: svg})
        myChart1.setOption(optionGen(arr));
      })
    }

    onMounted(() => {
      if (store.state.matchDetails.stats) {
        echarts.use([
          TooltipComponent,
          VisualMapComponent,
          GeoComponent,
          MapChart,
          CanvasRenderer
        ]);

        buildCharts()

        watch(() => props.stats, () => {
          processDmg()
          processPlayerWeapon()
        })
      }
    })

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

    window.onresize = () => {
      if (window.innerWidth <= 750) {
        width.value = getWindowWidth() - 20
        height.value = setHeight()
      }

      buildCharts()
    }

    watch(() => data.selectPlayer, () => {
      data.selectWeapon = 'All'
      processPlayerWeapon()
    })

    watch(() => data.selectWeapon, () => {
      processDmg()
    })

    return {props, data, store, processPlayerWeapon}
  }
}
</script>

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

  .select-group {
    display: flex;
    flex-direction: row;
    gap: 1rem;

    .form-select {
      background: var(--bs-secondary);
      color: var(--bs-primary);
      width: 250px;
    }
  }
}

@media (max-width: 600px) {
  .select-group {
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
  }
}
</style>
