<script setup lang="ts">
import Button from 'primevue/button';
import { invoke } from '@tauri-apps/api/core';
import { Package } from '../types';
import { pkgKey } from '../util';

const props = defineProps({
    pkg: Object as () => Package,
});

const install = async () => {
    if (props.pkg === undefined) {
        return;
    }

    try {
        await invoke('install_package', { key: pkgKey(props.pkg) });
    } catch (err) {
        console.error(err);
        if (props.pkg !== undefined) {
            props.pkg.js.busy = false;
        }
    }

    //if (rv === 'Deferred') { /* download progress */ }
};

const remove = async () => {
    if (props.pkg === undefined) {
        return;
    }

    await invoke('delete_package', {
        key: pkgKey(props.pkg),
    });
};
</script>

<template>
    <Button
        v-if="pkg?.loc"
        rounded
        icon="pi pi-trash"
        severity="danger"
        aria-label="remove"
        size="small"
        class="self-center ml-4"
        style="width: 2rem; height: 2rem"
        :loading="pkg?.js.busy"
        v-on:click="remove()"
    />

    <Button
        v-else
        rounded
        icon="pi pi-plus"
        severity="success"
        aria-label="install"
        size="small"
        class="self-center ml-4"
        style="width: 2rem; height: 2rem"
        :loading="pkg?.js.busy"
        v-on:click="install()"
    />
</template>
