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

    console.log($appState.currentRequest);

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

    let alert;
    let success = false;
    async function sendResponse() {
        try {
            await invoke('respond', {response: $appState.currentRequest.response});
            success = true;
            window.setTimeout(cleanupRequest, rehideDelay);
        }
        catch (e) {
            // reset to null so that we go back to asking for approval
            $appState.currentRequest.response = null;
            // setTimeout forces this to not happen until the alert has been rendered
            window.setTimeout(() => alert.setError(e), 0);
        }
    }

    async function handleResponseCollected() {
        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}
    <!-- if a response hasn't been collected, ask for it -->
    <div class="flex flex-col space-y-4 p-4 m-auto max-w-xl h-screen items-center justify-center">
        <ErrorAlert bind:this={alert}>
            <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>

        <CollectResponse  on:response={handleResponseCollected} />
    </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}
