<script>
    import { onMount } from 'svelte';
    import { slide, fade } from 'svelte/transition';
    import { writable } from 'svelte/store';
    import { invoke } from '@tauri-apps/api/core';

    import AwsCredential from './credentials/AwsCredential.svelte';
    import Icon from '../ui/Icon.svelte';
    import Nav from '../ui/Nav.svelte';

    let show = false;

    let records = []
    let defaults = writable({});
    async function loadCreds() {
        records = await invoke('list_credentials');
        let pairs = records.filter(r => r.is_default).map(r => [r.credential.type, r.id]);
        $defaults = Object.fromEntries(pairs);
    }
    onMount(loadCreds);

    function newAws() {
        records.push({
            id: crypto.randomUUID(),
            name: null,
            is_default: false,
            credential: {type: 'AwsBase', AccessKeyId: null, SecretAccessKey: null},
            isNew: true,
        });
        records = records;
    }
</script>


<Nav>
    <h1 slot="title" class="text-2xl font-bold">Credentials</h1>
</Nav>

<div class="max-w-xl mx-auto mb-12 flex flex-col gap-y-4 justify-center">
    <div class="divider">
        <h2 class="text-xl font-bold">AWS Access Keys</h2>
    </div>

    {#if records.length > 0}
        {#each records as record (record.id)}
            <AwsCredential {record} {defaults} on:update={loadCreds} />
        {/each}
        <button class="btn btn-primary btn-wide mx-auto" on:click={newAws}>
            <Icon name="plus-circle-mini" class="size-5" />
            Add
        </button>
    {:else}
        <div class="flex flex-col gap-6 items-center rounded-box border-2 border-dashed border-neutral-content/30 p-6">
            <div>You have no saved AWS credentials.</div>
            <button class="btn btn-primary btn-wide mx-auto" on:click={newAws}>
                <Icon name="plus-circle-mini" class="size-5" />
                Add
            </button>
        </div>
    {/if}

</div>
