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

    export let appState;

    const dispatch = createEventDispatcher();

    let errorMsg = null;
    let passphrase = '';
    async function unlock() {
        console.log('invoking unlock command.')

        try {
            await invoke('unlock', {passphrase});
            appState.credentialStatus = 'unlocked';
            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="{unlock}">
    <div class="text-gray-200">Enter your passphrase:</div>
    <input autofocus class="text-gray-200 bg-zinc-800" type="password" placeholder="correct horse battery staple" bind:value="{passphrase}" />
    <Button on:click={unlock}>Submit</Button>
</form>
