<script setup lang="ts">
import { Ref, computed, ref } from 'vue';
import Button from 'primevue/button';
import Fieldset from 'primevue/fieldset';
import ModListEntry from './ModListEntry.vue';
import ModTitlecard from './ModTitlecard.vue';
import { invoke } from '../invoke';
import { usePkgStore, usePrfStore } from '../stores';
import { Package } from '../types';
import { pkgKey } from '../util';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const props = defineProps({
    search: String,
});

const pkgs = usePkgStore();
const prf = usePrfStore();
const empty = ref(false);
const gameSublist: Ref<string[]> = ref([]);

invoke('get_game_packages', {
    game: prf.current?.meta.game ?? null,
}).then((list) => {
    gameSublist.value = list as string[];
});

const group = computed(() => {
    const res = Object.assign(
        {},
        Object.groupBy(
            pkgs.allLocal
                .filter((p) => gameSublist.value.includes(pkgKey(p)))
                .filter(
                    (p) =>
                        props.search === undefined ||
                        p.name
                            .toLowerCase()
                            .includes(props.search.toLowerCase()) ||
                        p.namespace
                            .toLowerCase()
                            .includes(props.search.toLowerCase())
                )
                .sort((p1, p2) => p1.namespace.localeCompare(p2.namespace))
                .sort((p1, p2) => p1.name.localeCompare(p2.name)),
            ({ namespace }) => namespace
        )
    );
    empty.value = Object.keys(res).length === 0;
    return res;
});

const missing = computed(() => {
    return prf.current?.data.mods.filter((m) => !pkgs.hasLocal(m)) ?? [];
});

const emptyVisible = ref(false);
setTimeout(() => (emptyVisible.value = true), 500);
</script>

<template>
    <Fieldset :legend="t('store.missing')" v-if="(missing?.length ?? 0) > 0">
        <div class="flex items-center" v-for="p in missing">
            <ModTitlecard
                show-namespace
                :pkg="
                    {
                        namespace: p.split('-')[0],
                        name: p.split('-')[1],
                    } as Package
                "
            />
            <Button
                rounded
                icon="pi pi-minus"
                severity="danger"
                aria-label="install"
                size="small"
                class="self-center ml-4"
                style="width: 2rem; height: 2rem"
                v-on:click="prf.togglePkg(p, false)"
            />
        </div>
    </Fieldset>
    <Fieldset v-for="(namespace, key) in group" :legend="key.toString()">
        <ModListEntry v-for="p in namespace" :pkg="p" />
    </Fieldset>
    <div v-if="empty === true && emptyVisible === true" class="text-3xl fadein">
        ∅
    </div>
</template>
