<script lang="ts">
    import {Button, ButtonGroup, Card, Input, InputAddon, StepIndicator, Tooltip} from 'flowbite-svelte';
    import {Password} from 'carbon-icons-svelte';
    import {info_banner, rpc, session, state, StateE, token, workingWrapperO, workingWrapperR} from '../store';
    import QRCode from 'qrcode-svg';

    const s = session.s;

    let step = 1;
    let code = '', secret_qr_code = '';
    let secret: string | null = null;
    let show_manual = false;

    async function startSetup(mail: boolean) {
        if (mail) {
            const resp = await workingWrapperO(() => rpc.Auth_tfa_setup_mail($token ?? ''));
            if (resp) {
                secret = null;
                step = 2;
            }
        } else {
            const resp = await workingWrapperR<string>(() => rpc.Auth_tfa_setup_totp($token ?? ''));
            if (resp != null) {
                secret = resp.replaceAll('=', '');
                secret_qr_code = new QRCode({
                    content: `otpauth://totp/MFileserver:${$s?.name ?? ''}?secret=${secret}&issuer=MFileserver`,
                    container: 'none',
                    padding: 0
                }).svg();
                step = 2;
            }
        }
    }

    async function completeSetup() {
        if (await workingWrapperO(() => rpc.Auth_tfa_complete($token ?? '', code))) {
            info_banner.set("Successfully set up two factor authentication");
            $state.s = StateE.LOGIN;
            token.set(null);
        }
    }

    function keyUp(e: KeyboardEvent) {
        if (e.key == 'Enter') completeSetup();
    }
</script>

<Card class="w-full max-w-lg">
    <StepIndicator steps={["Select type", "Finish setup"]} currentStep={step} size="h-2" class="mb-8"/>
    {#if step === 1}
        <ButtonGroup>
            <Button class="flex-1 flex-grow" color="primary" outline on:click={startSetup.bind(null, true)}>Mail</Button>
            <Tooltip>Receive a code via email when you want to log in</Tooltip>
            <Button class="flex-1 flex-grow" color="primary" outline on:click={startSetup.bind(null, false)}>Authenticator</Button>
            <Tooltip>Use a program like "Google Authenticator" to get a code when you want to log in</Tooltip>
        </ButtonGroup>
    {:else if step === 2}
        {#if secret == null}
            <p>A code has been sent to your mailbox</p>
        {:else}
            <svg class="w-full mb-4" viewBox="0 0 256 256" height="100%">{@html secret_qr_code}</svg>
            {#if show_manual}
                <pre class="w-full mb-4 bg-gray-100">{secret}</pre>
            {:else}
                <button class="w-full mb-4 bg-gray-200 rounded-lg" on:click={() => (show_manual = true)}>Click for manual input code</button>
            {/if}
        {/if}
        <ButtonGroup class="w-full mb-4">
            <InputAddon><Password /></InputAddon>
            <Input type="text" placeholder="Code" bind:value={code} on:keyup={keyUp}></Input>
        </ButtonGroup>
        <Button class="w-full" on:click={completeSetup}>Complete setup</Button>
    {/if}
</Card>
