<script lang="ts">
    import {rpc, show_working} from '../store';
    import {Button, ButtonGroup, Modal} from 'flowbite-svelte';
    import {afterUpdate, createEventDispatcher} from 'svelte';

    let show_confirm = false;
    let show_modal = false;
    let pre_element: HTMLElement|null = null;
    let text = '';
    let nodes: number[] = [];

    const dispatch = createEventDispatcher<{reload_node: null}>();

    async function real_delete() {
        show_confirm = false;
        show_modal = true;
        text = '';
        show_working.set(true);

        await new Promise<void>((resolve) => {
            rpc.deleteNodes(nodes, v => {
                if (v == null)
                    resolve();
                else {
                    text += v;
                }
            });
        });

        show_working.set(false);
        show_modal = false;
        dispatch('reload_node');
    }

    export const del = async (n: number[]) => {
        nodes = n;
        show_confirm = true;
    };

    afterUpdate(() => {
        if (pre_element)
            pre_element.scroll({ top: pre_element.scrollHeight, behavior: 'instant' });
    });
</script>

<Modal bind:open={show_confirm} dismissable={false} title="Do you really want to delete these files?">
    <ButtonGroup class="w-full flex flex-nowrap">
        <Button class="flex-1" color="green" on:click={() => show_confirm = false}>No</Button>
        <Button class="flex-1" color="red" on:click={real_delete}>Yes</Button>
    </ButtonGroup>
</Modal>

<Modal bind:open={show_modal} dismissable={false} size="xl" title="Deleting" bodyClass="h-full p-0 space-y-0" class="h-screen-90">
    <pre bind:this={pre_element} class="bg-gray-200 text-gray-600 px-4 py-2 h-full overflow-y-auto overscroll-contain rounded-b">{text}</pre>
</Modal>
