<script>
    import { invoke } from '@tauri-apps/api/tauri';
    import { emit } from '@tauri-apps/api/event';
    import { onMount } from 'svelte';

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


    let errorMsg = null;
    let alert;
    let passphrase = '';
    let loadTime = 0;
    let saving = false;
    async function unlock() {
        // The hotkey for navigating here from homepage is Enter, which also
        // happens to trigger the form submit event
        if (Date.now() - loadTime < 10) {
            return;
        }

        try {
            saving = true;
            let r = await invoke('unlock', {passphrase});
            $appState.credentialStatus = 'unlocked';
            emit('credentials-event', 'unlocked');
            if ($appState.currentRequest) {
                navigate('Approve');
            }
            else {
                navigate('Home');
            }
        }
        catch (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', 'unlock-canceled');
        navigate('Home');
    }

    onMount(() => {
        loadTime = Date.now();
    })
</script>


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

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

    <!-- svelte-ignore a11y-autofocus -->
    <input autofocus name="password" type="password" placeholder="correct horse battery staple" bind:value="{passphrase}" class="input input-bordered" />

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