<script setup lang="ts">
import { Ref, computed, ref } from 'vue';
import InputText from 'primevue/inputtext';
import Select from 'primevue/select';
import ToggleSwitch from 'primevue/toggleswitch';
import { listen } from '@tauri-apps/api/event';
import * as path from '@tauri-apps/api/path';
import { readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';
import OptionCategory from '../OptionCategory.vue';
import OptionRow from '../OptionRow.vue';
import { invoke } from '../../invoke';
import { usePkgStore, usePrfStore } from '../../stores';
import { Feature } from '../../types';
import { hasFeature, pkgKey } from '../../util';

const pkgs = usePkgStore();
const prf = usePrfStore();

const aimeCode = ref('');
const coms: Ref<{ [key: string]: number }> = ref({});

prf.reload();

const aimeCodeModel = computed({
    get() {
        return aimeCode.value;
    },
    async set(value: string) {
        aimeCode.value = value;
        if (value.match(/^[0-9]{20}$/) || value.length === 0) {
            const aime_path = await path.join(await prf.configDir, 'aime.txt');
            await writeTextFile(aime_path, aimeCode.value);
        }
    },
});

const aimeCodePaste = (ev: ClipboardEvent) => {
    aimeCodeModel.value =
        ev.clipboardData
            ?.getData('text/plain')
            .split('')
            .filter((c) => c >= '0' && c <= '9')
            .join('') ?? '';
};

const load = async () => {
    const aime_path = await path.join(await prf.configDir, 'aime.txt');
    aimeCode.value = await readTextFile(aime_path).catch(() => '');
};

invoke('list_com_ports').then((newComs) => {
    coms.value = newComs as typeof coms.value;
});

listen('reload-aime-code', load);

load();
</script>

<template>
    <OptionCategory title="Aime">
        <OptionRow
            title="Aime type"
            tooltip="Additional Aime plugins can be downloaded from the package store."
        >
            <Select
                v-model="prf.current!.data.sgt.aime"
                :options="[
                    { title: 'hardware', value: 'Disabled' },
                    { title: 'segatools built-in emulation', value: 'BuiltIn' },
                    ...pkgs.byFeature(Feature.Aime).map((p) => {
                        return {
                            title: pkgKey(p),
                            value: hasFeature(p, Feature.AMNet)
                                ? { AMNet: pkgKey(p) }
                                : { Other: pkgKey(p) },
                        };
                    }),
                ]"
                placeholder="none"
                option-label="title"
                option-value="value"
            ></Select>
        </OptionRow>
        <OptionRow
            title="Aime code"
            v-if="prf.current!.data.sgt.aime !== 'Disabled'"
        >
            <InputText
                class="shrink"
                size="small"
                :maxlength="20"
                placeholder="00000000000000000000"
                v-model="aimeCodeModel"
                @paste="aimeCodePaste"
            />
        </OptionRow>
        <div v-if="prf.current!.data.sgt.aime?.hasOwnProperty('AMNet')">
            <OptionRow title="Server name">
                <InputText
                    class="shrink"
                    size="small"
                    placeholder="CHUNI-PENGUIN"
                    :maxlength="50"
                    v-model="prf.current!.data.sgt.amnet.name"
                />
            </OptionRow>
            <OptionRow title="Server address">
                <InputText
                    class="shrink"
                    size="small"
                    placeholder="http://+:6070"
                    :maxlength="50"
                    v-model="prf.current!.data.sgt.amnet.addr"
                />
            </OptionRow>
            <OptionRow
                title="Use AiMeDB for physical cards"
                tooltip="Whether physical cards should use AiMeDB to retrieve access codes. If the game is using a hosted network, enable this option to load the same account data/profile as you would get on a physical cab."
            >
                <ToggleSwitch v-model="prf.current!.data.sgt.amnet.physical" />
            </OptionRow>
        </div>
        <OptionRow
            title="Aime serial port"
            tooltip="Ports can be checked in Devices and Printers or at googlechromelabs.github.io/serial-terminal
                For AIC Pico, the AIME port should be selected."
            v-if="prf.current!.data.sgt.aime === 'Disabled'"
        >
            <Select
                v-model="prf.current!.data.sgt.aime_port"
                :options="[
                    { title: 'default', value: null },
                    ...Object.entries(coms ?? {}).map(([title, value]) => {
                        return {
                            title,
                            value,
                        };
                    }),
                ]"
                placeholder="default"
                option-label="title"
                option-value="value"
            ></Select>
        </OptionRow>
    </OptionCategory>
</template>
