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

    import { appState } from '../lib/state.js';
    import { navigate } from '../lib/routing.js';
    import Link from '../ui/Link.svelte';
    import ErrorAlert from '../ui/ErrorAlert.svelte';
    import Spinner from '../ui/Spinner.svelte';


    let errorMsg = null;
    let alert;
    let AccessKeyId, SecretAccessKey, passphrase, confirmPassphrase

    function confirm() {
        if (passphrase !== confirmPassphrase) {
            errorMsg = 'Passphrases do not match.'
        }
    }

    let saving = false;
    async function save() {
        if (passphrase !== confirmPassphrase) {
            alert.shake();
            return;
        }

        let credentials = {AccessKeyId, SecretAccessKey};
        try {
            saving = true;
            await invoke('save_credentials', {credentials, passphrase});
            emit('credentials-event', 'entered');
            if ($appState.currentRequest) {
                navigate('Approve');
            }
            else {
                navigate('Home');
            }
        }
        catch (e) {
            window.error = e;
            const root = getRootCause(e);
            if (e.code === 'GetSession' && root.code) {
                errorMsg = `Error response from AWS (${root.code}): ${root.msg}`;
            }
            else {
                errorMsg = e.msg;
            }

            // if the alert already existed, shake it
            if (alert) {
                alert.shake();
            }

            saving = false;
        }
    }

    function cancel() {
        emit('credentials-event', 'enter-canceled');
        navigate('Home');
    }
</script>



<form action="#" on:submit|preventDefault="{save}" class="form-control space-y-4 max-w-sm m-auto p-4 h-screen justify-center">
    <h2 class="text-2xl font-bold text-center">Enter your credentials</h2>

    {#if errorMsg}
        <ErrorAlert bind:this="{alert}">{errorMsg}</ErrorAlert>
    {/if}

    <input type="text" placeholder="AWS Access Key ID" bind:value="{AccessKeyId}" class="input input-bordered" />
    <input type="password" placeholder="AWS Secret Access Key" bind:value="{SecretAccessKey}" class="input input-bordered" />
    <input type="password" placeholder="Passphrase" bind:value="{passphrase}" class="input input-bordered" />
    <input type="password" placeholder="Re-enter passphrase" bind:value={confirmPassphrase} class="input input-bordered" on:change={confirm} />

    <button type="submit" class="btn btn-primary">
        {#if saving }
            <Spinner class="w-5 h-5" thickness="12"/>
        {:else}
            Submit
        {/if}
    </button>
    <Link target={cancel} hotkey="Escape">
        <button class="btn btn-sm btn-outline w-full">Cancel</button>
    </Link>
</form>
