<script setup lang="ts">
import { Modal } from '@/components';
import { MarketType, MarketTypeLabel } from '@/market';
import { ref } from 'vue';
import { AcquiredType, acquiredTypesToSorted } from './AcquiredType';
import { useAcquiredTypesStore } from './acquisition';


const acquiredTypesStore = useAcquiredTypesStore();

const modalOpen = ref<boolean>(false);
const type = ref<MarketType>();
const count = ref(1);
const types = ref<AcquiredType[]>([]);

const open = (t: AcquiredType[]) => {
    if (t.length === 0) {
        return;
    }

    types.value = acquiredTypesToSorted(t);
    type.value = t[0].type;
    count.value = 1;
    modalOpen.value = true;
}
const remove = async () => { 
    if (!types.value) {
        modalOpen.value = false;
        return;
    }

    let c = count.value;

    for (const type of types.value) {
        const remaining = type.remaining;

        await acquiredTypesStore.removeAcquiredType(type.id, c);
        c -= remaining;
        if (c <= 0) {
            break;
        }
    }
    modalOpen.value = false;
}

defineExpose({ open });
</script>

<template>
    <Modal v-model:open="modalOpen">
        <div class="bg-slate-800 rounded">
            <MarketTypeLabel v-if="type" class="m-1" :id="type.id" :name="type.name" hideCopy />
            <hr />
            <div class="flex p-4">
                <div class="flex me-2 mb-auto">
                    <span>Count: </span>
                    <div class="ms-2">
                        <input type="number" min="0" step="1" v-model="count" @keyup.enter="remove" />
                        <div>
                            <button class="px-2 mt-2 bg-slate-600 hover:bg-slate-700 border rounded cursor-pointer" @click="count = types.reduce((acc, t) => acc + t.remaining, 0)">All</button>
                        </div>
                    </div>
                </div>
                <button class="mb-auto" @click="remove">Remove</button>
            </div>
        </div>
    </Modal>
</template>