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

    import ErrorAlert from '../ui/ErrorAlert.svelte';
    import CollectResponse from './approve/CollectResponse.svelte';
    import ShowResponse from './approve/ShowResponse.svelte';
    import Unlock from './Unlock.svelte';


    // Extra 50ms so the window can finish disappearing before the redraw
    const rehideDelay = Math.min(5000, $appState.config.rehide_ms + 50);

    let error, alert;
    let success = false;
    async function sendResponse() {
        try {
            await invoke('respond', {response: $appState.currentRequest.response});
            success = true;
            window.setTimeout(cleanupRequest, rehideDelay);
        }
        catch (e) {
            if (error) {
                alert.shake();
            }
            error = e;
        }
    }

    async function handleResponse() {
        if (
            $appState.sessionStatus === 'unlocked'
            || $appState.currentRequest.response.approval === 'Denied'
        ) {
            await sendResponse();
        }
    }
</script>


{#if success}
    <!-- if we have successfully sent a response, show it -->
    <ShowResponse />
{:else if !$appState.currentRequest?.response || error}
    <!-- if there's no response, or if there was an error sending it, ask for response -->
    <div class="flex flex-col space-y-4 p-4 m-auto max-w-xl h-screen items-center justify-center">
        {#if error}
            <ErrorAlert bind:this={alert}>
                {error.msg}
                <svelte:fragment slot="buttons">
                    <button class="btn btn-sm btn-alert-error" on:click={cleanupRequest}>Cancel</button>
                    <button class="btn btn-sm btn-alert-error" on:click={sendResponse}>Retry</button>
                </svelte:fragment>
            </ErrorAlert>
        {/if}

        <CollectResponse  on:response={handleResponse} />
    </div>
{:else if $appState.sessionStatus === 'locked'}
    <!-- if session is locked and we do have a response, we must be waiting for unlock -->
    <Unlock on:unlocked={sendResponse} />
{:else}
    <!-- failsafe sanity check -->
    <ErrorAlert>
        Something is wrong. This message should never show up during normal operation.
    </ErrorAlert>
{/if}
