<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';


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

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

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

        let credentials = {AccessKeyId, SecretAccessKey};
        try {
            await invoke('save_credentials', {credentials, passphrase});
            if ($appState.currentRequest) {
                navigate('Approve');
            }
            else {
                navigate('Home');
            }
        }
        catch (e) {
            if (e.code === "GetSession") {
                let root = getRootCause(e);
                errorMsg = `Error response from AWS (${root.code}): ${root.msg}`;
            }
            else {
                errorMsg = e.msg;
            }

            if (alert) {
                alert.shake();
            }
        }
    }
</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} />

    <input type="submit" class="btn btn-primary" />
    <Link target="Home" hotkey="Escape">
        <button class="btn btn-sm btn-outline w-full">Cancel</button>
    </Link>
</form>
