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

import { appState, acceptRequest } 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);

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

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)
    }
});

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

acceptRequest();
</script>


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