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

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

    let api_token = "";

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

    let owned_org_id;
    let owned_org_orginfo;
    let owns_org = false;

    let orgs = {};

    // 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 ORG LIST
        // we need to know what orgs this user has access to
        org_list = await list_org(api_token);
        if (typeof org_list === "string") {
            // Error
            logger.error(org_list);
            fullPageError = true;
            fullPageErrorTitle = t('admin.apierror.loadorg');
            fullPageErrorSubtitle = t('admin.apierror.' + org_list);
            return;
        }

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

        owned_org_id = user_info.data.actor.organizationID;
        if (owned_org_id !== "") {
            // the user actually owns an org
            logger.info("User owns an org");
            owns_org = true;
            owned_org_orginfo = await org(owned_org_id as number, api_token);
            if (typeof owned_org_orginfo === "string") {
                logger.error(owned_org_orginfo);
                fullPageError = true;
                fullPageErrorTitle = t('admin.apierror.loadownedorg');
                fullPageErrorSubtitle = t('admin.apierror.' + owned_org_orginfo);
                return;
            }
        } else {
            logger.info("User does not own an org");
        }

        // GET INFO ABOUT ALL THE ORGS
        for (let i = 0; i < org_list.length; i++) {
            let org_id = org_list[i];
            if (org_id === owned_org_id) continue;
            let org_info = await org(org_id as number, api_token);
            if (typeof org_info === "string") {
                logger.error(org_info);
                fullPageError = true;
                fullPageErrorTitle = t('admin.apierror.loadunownedorg');
                fullPageErrorSubtitle = t('admin.apierror.' + org_info);
                return;
            }
            orgs[org_info.name] = org_info;
        }

        logger.info("Loaded " + org_list.length + " associated orgs, finish displayDataLoad");
    })

    function setOrg(to) {
        window.location.href = "/org/" + to;
    }

    function newOrg() {
        window.location.href = "/org/new";
    }

    function joinOrg() {
        window.location.href = "/org/join";
    }
</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">
            <!-- org selector -->
            <h1 class="font-semibold text-xl">Select an organization to manage</h1>
            <div class="bg-slate-200 dark:bg-slate-700 rounded p-2 mt-2">
                <div class="grid grid-cols-1 divide-width divide-y divide-black dark:divide-gray-100">
                    <div>
                        {#if owns_org}
                            <div class="cursor-pointer flow-root transition hover:bg-slate-300 dark:hover:bg-slate-600 rounded m-2 p-2 group"
                                 on:click={() => {setOrg(owned_org_id)}}>
                                <span class="float-left cursor-pointer text-md">Your organization</span>
                                <span class="float-right cursor-pointer text-right text-md font-light text-slate-200 dark:text-slate-700 group-hover:text-slate-200">Next &rarr;</span>
                            </div>
                        {:else}
                            <div class="cursor-pointer flow-root transition hover:bg-slate-300 dark:hover:bg-slate-600 rounded m-2 p-2 group"
                                 on:click={() => {newOrg()}}>
                                <span class="float-left cursor-pointer text-md">+ Create an organization</span>
                            </div>
                        {/if}
                    </div>
                    <!--
                                        <div>
                                            <h4 class="ml-0.5 text-xs font-bold text-gray-200 dark:text-gray-400 mt-0.5">Organizations you have access to</h4>
                                            <div class="cursor-pointer flow-root transition hover:bg-slate-300 dark:hover:bg-slate-600 rounded m-2 p-2 group" on:click={() => {setOrg("1")}}>
                                                <span class="float-left cursor-pointer text-md">core@e3t.cc's organization</span>
                                                <span class="float-right cursor-pointer text-right text-md font-light text-slate-200 dark:text-slate-700 group-hover:text-slate-200">Next &rarr;</span>
                                            </div>

                                            <div class="cursor-pointer flow-root transition hover:bg-slate-300 dark:hover:bg-slate-600 rounded m-2 p-2 group" on:click={() => {setOrg("1")}}>
                                                <span class="float-left cursor-pointer text-md">core@coredoes.dev's organization</span>
                                                <span class="float-right cursor-pointer text-right text-md font-light text-slate-200 dark:text-slate-700 group-hover:text-slate-200">Next &rarr;</span>
                                            </div>

                </div>
                -->

                <div>
                    <div class="cursor-pointer flow-root transition hover:bg-slate-300 dark:hover:bg-slate-600 rounded m-2 p-2 group"
                         on:click={() => {joinOrg()}}>
                        <span class="float-left cursor-pointer text-md">+ Join an existing organization</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>

{/if}