<template>
  <div class="d-flex flex-row">
    <v-text-field
      class="filter flex-1-0"
      placeholder="Filter by Name"
      v-model="filtervalue"
    ></v-text-field>
  </div>
  <v-table>
    <thead>
      <tr>
        <th class="text-left">ID</th>
        <th class="text-left">Character</th>
        <th class="text-left">Role</th>
        <th class="text-left">Player</th>
        <th class="text-left">Status</th>
        <th class="text-left">Last Game</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="character in characters">
        <td>
          <a v-bind:href="`/#/characters/${character.id}`">{{ character.id }}</a>
        </td>
        <td>
          <a v-bind:href="`/#/characters/${character.id}`">{{ character.characterName }}</a>
        </td>
        <td>{{ character.role }}</td>
        <td>{{ character.playerName }}</td>
        <td>{{ character.status }}</td>
        <td>{{ character.lastGame }}</td>
        <td>0</td>
      </tr>
    </tbody>
  </v-table>
  <v-pagination
    :model-value="page"
    :length="pageCount"
    @update:modelValue="setPage($event)"
  ></v-pagination>
</template>

<style type="text/css"></style>

<script setup lang="ts">
import { onMounted, onCreated, ref } from 'vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

const characters = ref({})
const pageCount = ref(1)
const page = ref(1)

let count = 10

const filtervalue = ref('')

async function loadData() {
  const response = await axios.post('/api/character', {
    page: `${page.value - 1}`,
    count: `10`,
    orderBy: 'id',
    filter: filtervalue.value ? `characterName:"${filtervalue.value}"` : ''
  })

  characters.value = response.data.characterData
  pageCount.value = response.data.pageCount
}

function setPage(targetPage: number) {
  router.replace({ query: { page: targetPage, filter: route.query.filter } })
}

watch(route, (newValue, oldValue) => {
  if (!route.query.page) {
    router.replace({ query: { page: 1, filter: route.query.filter } })
    page.value = 1
  } else {
    page.value = Number(route.query.page)
  }
  page.value = Number(route.query.page)
  loadData()
})

let debounce = null
watch(filtervalue, (newFilter, oldFilter) => {
  debounce = clearTimeout(debounce)
  debounce = setTimeout(() => {
    router.replace({ query: { page: route.query.page, filter: newFilter } })
  }, 500)
})

onMounted(async () => {
  if (!route.query.page) {
    router.replace({ query: { page: 1 } })
    page.value = 1
  } else {
    page.value = Number(route.query.page)
  }
  if (route.query.filter) {
    filtervalue.value = route.query.filter
  }
  loadData()
})
</script>
