<script setup lang="ts">
import { Ref, computed, ref } from 'vue';
import Button from 'primevue/button';
import { listen } from '@tauri-apps/api/event';
import { invoke } from '../invoke';
import { usePrfStore } from '../stores';

const prf = usePrfStore();

type StartStatus = 'ready' | 'preparing' | 'running';
const startStatus: Ref<StartStatus> = ref('ready');

const startline = async () => {
    startStatus.value = 'preparing';
    try {
        await invoke('startline');
    } catch (e) {
        startStatus.value = 'ready';
    }
};

const kill = async () => {
    await invoke('kill');
    startStatus.value = 'ready';
};

const disabledTooltip = computed(() => {
    if (prf.current?.sgt.target.length === 0) {
        return 'The game path must be specified';
    }
    if (prf.current?.sgt.amfs.length === 0) {
        return 'The amfs path must be specified';
    }
    return null;
});

listen('launch-start', () => {
    startStatus.value = 'running';
});

listen('launch-end', () => {
    startStatus.value = 'ready';
});
</script>

<template>
    <Button
        v-if="startStatus === 'ready'"
        v-tooltip="disabledTooltip"
        :disabled="disabledTooltip !== null"
        icon="pi pi-play"
        label="START"
        aria-label="start"
        size="small"
        class="m-2.5"
        @click="startline()"
    />
    <Button
        v-else-if="startStatus === 'preparing'"
        disabled
        icon="pi pi-spin pi-spinner"
        label="START"
        aria-label="start"
        size="small"
        class="m-2.5"
    />
    <Button
        v-else
        :disabled="false"
        icon="pi pi-ban"
        label="STOP"
        aria-label="stop"
        size="small"
        class="m-2.5"
        @click="kill()"
    />
</template>
