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

import { appState, acceptRequest, cleanupRequest } from './lib/state.js';
import { views, currentView, navigate } from './lib/routing.js';


$views = import.meta.glob('./views/*.svelte', {eager: true});
navigate('Home');

invoke('get_config').then(config => $appState.config = config);
invoke('get_session_status').then(status => $appState.credentialStatus = status);
getVersion().then(version => $appState.appVersion = version);

listen('credentials-request', (tauriEvent) => {
    $appState.pendingRequests.put(tauriEvent.payload);
});

listen('request-cancelled', (tauriEvent) => {
    const id = tauriEvent.payload;
    if (id === $appState.currentRequest?.id) {
        cleanupRequest();
    }
    else {
        const found = $appState.pendingRequests.find_remove(r => r.id === id);
    }
});

listen('launch-terminal-request', async (tauriEvent) => {
    if ($appState.currentRequest === null) {
        let status = await invoke('get_session_status');
        if (status === 'locked') {
            navigate('Unlock');
        }
        else if (status === 'empty') {
            navigate('EnterCredentials');
        }
        // else, session is unlocked, so do nothing
        // (although we shouldn't even get the event in that case)
    }
});

listen('locked', () => {
    $appState.credentialStatus = 'locked';
});

invoke('get_setup_errors')
    .then(errs => {
        $appState.setupErrors = errs.map(e => ({msg: e, show: true}));
    });

acceptRequest();
</script>


<svelte:window 
    on:click={() => invoke('signal_activity')}
    on:keydown={() => invoke('signal_activity')}
/>

<svelte:component this="{$currentView}" />
