<script lang="ts">
    import {onMount} from "svelte";
    import {enforce_auth, enforce_session} from "$lib/auth";
    import {Logger, logSetup} from "$lib/logger";
    import {list_org} from "$lib/orgs";
    import {t} from "$lib/i18n";
    import FullPageError from "../../../components/FullPageError.svelte";
    import {get_user_info} from "$lib/auth";
    import {org} from "$lib/orgs";
    import type {Organization} from "$lib/orgs";
    import {API_ROOT} from "$lib/config";
    import {fetch_timeout} from "$lib/util";

    let logger = new Logger("admin/+page.svelte");
    logSetup();

    let api_token = "";

    let fullPageError = false;
    let fullPageErrorTitle = "";
    let fullPageErrorSubtitle = "";

    let user_info;

    let org_ip_range = "172.16.0.0/24";
    let org_subnets = "";
    let org_groups = "";
    let hasError_iprange = false;
    let error_iprange = "";

    let hasError_subnet = false;
    let error_subnet = "";

    let isloading = false;
    let canSubmit = true;

    function recalcCansubmit() {
        canSubmit = hasError_iprange || fullPageError || hasError_subnet;
    }

    // this page requires session and mfa auth.
    onMount(async () => {
        let st_result = await enforce_session();
        if (!st_result[0]) {
            // Session token is invalid. redirect to login
            window.location = "/auth/login";
            return;
        }
        let at_result = await enforce_auth();
        if (!at_result[0]) {
            // Auth token is invalid. Redirect to mfa page.
            window.location = "/auth/mfa";
            return;
        }
        // user is fully authenticated and permitted to proceed
        api_token = at_result[1];
        logger.info("User authenticated successfully");

        // GET USER INFO
        user_info = await get_user_info(api_token);
        if (typeof user_info === "string") {
            logger.error(user_info);
            fullPageError = true;
            fullPageErrorTitle = t('admin.apierror.loaduser');
            fullPageErrorSubtitle = t('admin.apierror.' + user_info);
            return;
        }

        let owned_org_id = user_info.data.actor.organizationID;
        if (owned_org_id !== "") {
            logger.error("User owns an org already");
            window.location.href = "/admin";
        }
    })

    let showAdditionalConstraints = false;

    function handle(listfield: string): string[] {
        if (listfield == "") {
            return []
        } else {
            return listfield.split(',')
        }
    }

    async function doCreateFlow() {
        // STEP ONE: Create the org
        logger.info("Creating organization");
        let created_org_id;



        try {
            let resp = await fetch_timeout(`${API_ROOT}/v1/org`, {
                'method': 'POST',
                'headers': {
                    'Authorization': 'Bearer ' + api_token
                },
                'body': JSON.stringify({
                    'ip_ranges': handle(org_ip_range),
                    'subnet_ranges': handle(org_subnets),
                    'groups': handle(org_groups)
                })
            });
            if (!resp.ok) {
                if (resp.status === 422) {
                    // we had an invalid input
                    logger.error(`Invalid input`);
                    fullPageError = true;
                    fullPageErrorTitle = t('neworg.apierror.orgcreate');
                    fullPageErrorSubtitle = t('neworg.apierror.invaliddata');
                    return;
                }
                let err = JSON.parse(await resp.text()).errors[0].message;
                logger.error(`${await resp.json().errors[0]}`);
                fullPageError = true;
                fullPageErrorTitle = t('neworg.apierror.orgcreate');
                fullPageErrorSubtitle = t('neworg.apierror.' + err);
                return;
            }
            let resp_objectified = JSON.parse(await resp.text());
            console.log(JSON.stringify(resp_objectified));
            created_org_id = resp_objectified.org_id;
            logger.info("Able to create organization with id " + created_org_id);
            logger.info("Org create success! Redirecting to manage page");
            window.location.href = "/org/" + created_org_id;
        } catch (e) {
            logger.error(`${e}`);
            fullPageError = true;
            fullPageErrorTitle = t('neworg.apierror.orgcreate');
            fullPageErrorSubtitle = t('neworg.apierror.' + `${e}`.replaceAll('.', ''));
            return;
        }
    }
</script>

{#if fullPageError}
    <FullPageError title="{fullPageErrorTitle}" subtitle="{fullPageErrorSubtitle}"/>
{:else}
    <div class="flex in-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8 h-max">
        <div class="w-full max-w-md m-auto">
            <div>
                <h1 class="font-semibold text-2xl">{t('neworg.title')}</h1>
                <h2 class="text-sm">{t('neworg.subtitle')}</h2>
                <h3 class="font-semibold mt-5">{t('neworg.firstcert')}</h3>
                <h3 class="text-sm">{t('neworg.cahelp')}</h3>
            </div>

            <form class="mt-5" action="#" method="POST" on:submit|preventDefault={doCreateFlow}>
                <div class=" rounded-md shadow-sm">
                    <label for="iprange" class="mb-5">{t('neworg.iprangeprompt')}</label>
                    <input bind:value={org_ip_range} id="iprange"
                           class="mt-2 dark:bg-slate-500 bg-gray-200 w-full rounded px-3 py-2 focus:outline-none focus:ring-purple-500 appearance-none">
                    <span class="text-sm block">{t('neworg.cidrhelp')}</span>
                    {#if hasError_iprange}
                        <span class="text-red-600 text-sm block">{error_iprange}</span>
                    {/if}
                </div>

                <label class="relative inline-flex items-center cursor-pointer mt-4 ">
                    <input bind:checked={showAdditionalConstraints} type="checkbox" class="sr-only peer">
                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-purple-600"></div>
                    <span class="ml-3 text-sm font-medium text-gray-900 dark:text-gray-300">{t('neworg.additionalConstraints')}</span>
                </label>

                {#if showAdditionalConstraints}
                    <div class=" rounded-md shadow-sm">
                        <label for="subnets" class="mb-5">{t('neworg.subnetprompt')}</label>
                        <input bind:value={org_subnets} id="subnets"
                               class="mt-2 dark:bg-slate-500 bg-gray-200 w-full rounded px-3 py-2 focus:outline-none focus:ring-purple-500 appearance-none">
                        <span class="text-sm block">{t('neworg.subnethelp')}</span>
                        {#if hasError_subnet}
                            <span class="text-red-600 text-sm block">{error_subnet}</span>
                        {/if}
                    </div>

                    <div class="mt-2 rounded-md shadow-sm">
                        <label for="groups" class="mb-5">{t('neworg.groupprompt')}</label>
                        <input bind:value={org_groups} id="groups"
                               class="mt-2 dark:bg-slate-500 bg-gray-200 w-full rounded px-3 py-2 focus:outline-none focus:ring-purple-500 appearance-none">
                        <span class="text-sm block">{t('neworg.grouphelp')}</span>
                        {#if hasError_subnet}
                            <span class="text-red-600 text-sm block">{error_subnet}</span>
                        {/if}
                    </div>
                {/if}

                <button disabled="{!canSubmit}"
                        class="bg-purple-400 dark:bg-purple-600 mt-4 w-full py-2 -space-y-px rounded-md shadow-sm place-content-center">
                    {#if !isloading}
                        {t('neworg.actionButtonText')}
                    {:else}
                        <svg class="animate-spin w-5 h-5 inline-block m-auto" xmlns="http://www.w3.org/2000/svg"
                             fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                    stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor"
                                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                    {/if}
                </button>
            </form>
        </div>
    </div>

{/if}