<template>
  <div class="wrapper">
    <div class="container-lg text-center">
      <h3>Recent matches</h3>
      <div v-if="data.matches">
        <MatchesTable :key="data.matches" :explore="true" :matches="data.matches" />

        <div class="load-more text-center">
          <button :key="scrollToPos(store.state.scroll_state)" class="btn border-2 btn-outline-info"
                  @click="setMoreMatches">Load More
          </button>
        </div>
      </div>

      <div v-else>
        <hr>
        <h6>There seems to be a problem loading the content</h6>
        <h6>Please try again later</h6>
      </div>
    </div>
  </div>
</template>

<script>
import {onBeforeUnmount, onMounted, reactive} from "vue";
import {GetMatches, LoadImage, LoadMoreMatchesExplore, MatchNotParsedTime, scrollToPos} from "@/utils";
import MatchesTable from "@/components/MatchesTable";
import {useStore} from "vuex";
import router from "@/router";

export default {
  name: 'ExploreView',
  components: {MatchesTable},
  setup() {
    document.title = "Matches | csgoWTF"

    const store = useStore()

    const data = reactive({
      matches: []
    })

    const setMoreMatches = async () => {
      const res = await LoadMoreMatchesExplore(store, data.matches[data.matches.length - 1].date)

      if (res !== null)
        res.forEach(e => data.matches.push(e))

      scrollToPos(window.scrollY)

      // console.log(data.matches)
    }

    onMounted(async () => {
      data.matches = await GetMatches(store)

      if (data.matches !== null) {
        if (data.matches[0].map) {
          await LoadImage(data.matches[0].map)
        } else if (!data.matches[0].map && MatchNotParsedTime(data.matches[0].date) && data.matches[1].map) {
          await LoadImage(data.matches[1].map)
        } else {
          await LoadImage('random')
        }
      } else {
        document.querySelector('.bg-img').style.display = 'none'
      }

      scrollToPos(store.state.scroll_state)

      // if (data.matches) {
      //   console.log(data.matches)
      // }

      document.getElementById('app').style.background = 'rgba(0, 0, 0, .7)'
      document.querySelector('.bg-img').style.display = 'initial'
    })

    onBeforeUnmount(() => {
      store.commit('changeScrollState', window.scrollY)

      router.beforeEach((to, from, next) => {
        if (!to.fullPath.match('/match/') && !from.fullPath.match('/match/')) {
          store.commit('changeScrollState', 0)
        }
        next()
      })
    })

    return {data, setMoreMatches, store, scrollToPos}
  }
}
</script>

<style lang="scss" scoped>
.container-lg {
  padding: 2rem;

  h3 {
    margin-bottom: 2rem;
  }

  .load-more {
    padding: 1rem 0;
  }
}

@media (max-width: 1200px) {
  .container-lg {
    padding: 2rem 1rem;
  }
}
</style>
