<script>
    import { createEventDispatcher } from 'svelte';
    import { invoke } from '@tauri-apps/api/core';
    import { appState } from '../../lib/state.js';

    import ErrorAlert from '../../ui/ErrorAlert.svelte';
    import Link from '../../ui/Link.svelte';
    import PassphraseInput from '../../ui/PassphraseInput.svelte';
    import ResetPassphrase from './ResetPassphrase.svelte';
    import Spinner from '../../ui/Spinner.svelte';

    export let cancellable = false;


    const dispatch = createEventDispatcher();

    let alert;
    let saving = false;
    let passphrase = '';
    let confirmPassphrase = '';

    // onChange only fires when an input loses focus, so always set the error if not set
    function onChange() {
        console.log(`onChange: passphrase=${passphrase}, confirmPassphrase=${confirmPassphrase}`)
        if (passphrase !== confirmPassphrase) {
            alert.setError('Passphrases do not match.');
        }
        else {
            alert.setError(null);
        }
    }
    // onInput fires on every keystroke, so only dismiss the error, don't create it
    function onInput() {
        console.log(`onInput: passphrase=${passphrase}, confirmPassphrase=${confirmPassphrase}`)
        if (passphrase === confirmPassphrase) {
            alert.setError(null);
        }
    }


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

        if (passphrase === '') {
            alert.setError('Passphrase is empty.')
            return;
        }

        saving = true;
        try {
            await alert.run(async () => {
                await invoke('set_passphrase', {passphrase})
                throw('something bad happened');
                $appState.sessionStatus = 'unlocked';
                dispatch('save');
            });
        }
        finally {
            saving = false;
        }
    }
</script>


<form class="form-control gap-y-4" on:submit|preventDefault={save}>
    <ErrorAlert bind:this={alert} />

    <label class="form-control w-full">
        <div class="label">
            <span class="label-text">Passphrase</span>
        </div>
        <PassphraseInput
            bind:value={passphrase}
            on:input={onInput}
            placeholder="correct horse battery staple"
        />
    </label>

    <label class="form-control w-full">
        <div class="label">
            <span class="label-text">Re-enter passphrase</span>
        </div>
        <PassphraseInput
            bind:value={confirmPassphrase}
            on:input={onInput} on:change={onChange}
            placeholder="correct horse battery staple"
        />
    </label>

    <button type="submit" class="btn btn-primary">
        {#if saving}
            <Spinner class="w-5 h-5" thickness="12"/>
        {:else}
            Submit
        {/if}
    </button>

    {#if cancellable}
        <Link target="Settings" hotkey="Escape">
            <button type="button" class="btn btn-outline btn-sm w-full">Cancel</button>
        </Link>
    {/if}

    {#if $appState.sessionStatus === 'locked'}
        <ResetPassphrase />
    {/if}
</form>
