<script>
    import { onMount, createEventDispatcher } from 'svelte';
    import { invoke } from '@tauri-apps/api/tauri';
    import { getRootCause } from '../lib/errors.js';

    export let appState;

    const dispatch = createEventDispatcher();
    let errorMsg = null;
    let AccessKeyId, SecretAccessKey, passphrase

    async function save() {
        console.log('Saving credentials.');
        let credentials = {AccessKeyId, SecretAccessKey};

        try {
            await invoke('save_credentials', {credentials, passphrase});
            if (appState.currentRequest) {
                dispatch('navigate', {target: 'ShowApproved'})
            }
            else {
                dispatch('navigate', {target: 'Home'})
            }
        }
        catch (e) {
            window.error = e;
            if (e.code === "GetSession") {
                let root = getRootCause(e);
                errorMsg = `Error response from AWS (${root.code}): ${root.msg}`;
            }
            else {
                errorMsg = e.msg;
            }
        }
    }
</script>

{#if errorMsg}
    <div class="text-red-400">{errorMsg}</div>
{/if}

<form action="#" on:submit|preventDefault="{save}">
    <div class="text-gray-200">AWS Access Key ID</div>
    <input class="text-gray-200 bg-zinc-800" type="text" bind:value="{AccessKeyId}" />

    <div class="text-gray-200">AWS Secret Access Key</div>
    <input class="text-gray-200 bg-zinc-800" type="password" bind:value="{SecretAccessKey}" />

    <div class="text-gray-200">Passphrase</div>
    <input class="text-gray-200 bg-zinc-800" type="password" bind:value="{passphrase}" />

    <input class="text-gray-200" type="submit" />
</form>
