<script>
    import { invoke } from '@tauri-apps/api/core';
    import { createEventDispatcher } from 'svelte';

    import ErrorAlert from '../../ui/ErrorAlert.svelte';

    let record;
    let modal;
    let alert;

    const dispatch = createEventDispatcher();

    export function confirm(r) {
        record = r;
        modal.showModal();
    }

    async function deleteCredential() {
        await invoke('delete_credential', {id: record.id})
        // closing the modal is dependent on the previous step succeeding
        modal.close();
        dispatch('confirm');
    }

    function credentialDescription(record) {
        if (record.credential.type === 'AwsBase') {
            return 'AWS credential';
        }
        else if (record.credential.type === 'Ssh') {
            return 'SSH key';
        }
        else {
            return `${record.credential.type} credential`;
        }
    }
</script>

<dialog bind:this={modal} class="modal">
    <div class="modal-box space-y-6">
        <ErrorAlert bind:this={alert} />
        <h3 class="text-lg font-bold">
            {#if record}
                Delete {credentialDescription(record)} "{record.name}"?
            {/if}
        </h3>
        <div class="modal-action">
            <form method="dialog" class="flex gap-x-4">
                <button
                    class="btn btn-outline"
                    on:click={() => alert.setError(null)}
                >
                    Cancel
                </button>

                <button
                    autofocus
                    class="btn btn-error"
                    on:click|preventDefault={() => alert.run(deleteCredential)}
                >
                    Delete
                </button>
            </form>
        </div>
    </div>
</dialog>
