<template>
  <ConfirmDialog></ConfirmDialog>

  <DataTable class="Tables" :value="props.gameTables">
    <Column field="table_name" header="Table Name" />

    <Column field="version" header="Ver"></Column>

    <Column field="table_link" header="Table Link">
      <template #body="slotProps">
        <a
          v-if="slotProps.data.active"
          :href="'http://' + slotProps.data.table_link + '.' + hostname"
        >
          http://{{ slotProps.data.table_link }}.{{ hostname }}/
        </a>
        <div v-if="!slotProps.data.active">
          http://{{ slotProps.data.table_link }}.{{ hostname }}/
        </div>
      </template>
    </Column>

    <Column header="Actions" v-if="showClose">
      <template #body="slotProps">
        <Button label="Close" @click="stopTable(slotProps.data)" />
      </template>
    </Column>

    <Column header="Actions" v-if="props.showFullActions">
      <template #body="slotProps">
        <div class="flex flex-row">
          <span class="flex"></span>
          <SplitButton
            label="Start"
            @click="startTable(slotProps.data)"
            :model="buildButtonModel(slotProps.data)"
          />
        </div>
      </template>
    </Column>
  </DataTable>
</template>

<style></style>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import axios from 'axios'
import Button from 'primevue/button'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Card from 'primevue/card'
import SplitButton from 'primevue/splitbutton'
import ConfirmDialog from 'primevue/confirmdialog'
import { useConfirm } from 'primevue/useconfirm'

import {
  GameTable,
  useActiveTables,
  useAllTables,
  startTable,
  hardStartTable,
  stopTable,
  deleteTable,
} from './game_tables'

const props = defineProps<{
  gameTables: any
  showClose?: boolean
  showFullActions?: boolean
}>()

const hostname = ref()
const router = useRouter()
const confirm = useConfirm()

onMounted(() => {
  hostname.value = location.host
})

function buildButtonModel(table: any) {
  return [
    {
      label: 'Edit',
      command: () => {
        router.push({ name: 'edit', params: { id: table.id } })
      },
    },
    { label: 'Restart' },
    {
      label: 'Hard Start',
      command: () => {
        hardStartTable(table)
      },
    },
    { separator: true },
    {
      label: 'Delete',
      command: () => {
        confirm.require({
          header: `Delete ${table.table_name}?`,
          message: "This will delete the table and all of it's data",
          accept: () => {
            deleteTable(table)
          },
        })
      },
    },
  ]
}
</script>
