<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";
    import {page} from "$app/stores";
    import OrgWrapper from "../../../../components/org/OrgWrapper.svelte";

    let logger = new Logger("org/[orgid]/roles/+page.svelte");
    logSetup();

    let orgid = $page.params.orgid;

    let api_token = "";

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

    let user_info;

    let roles = {
        'data': []
    };

    // 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 org_list: string | number[] = await list_org(api_token);
        if (typeof org_list === "string") {
            // Error
            logger.error(org_list);
            fullPageError = true;
            fullPageErrorTitle = t('org.apierror.loadorg');
            fullPageErrorSubtitle = t('org.apierror.' + org_list);
            return;
        }
        let list: number[] = org_list;

        if (!list.includes(Number(orgid))) {
            fullPageError = true;
            fullPageErrorTitle = t('org.apierror.notyourorg');
            fullPageErrorSubtitle = t('org.apierror.notyourorgexplainer');
            return;
        }

        try {
            let resp = await fetch_timeout(`${API_ROOT}/v1/org/${orgid}/roles`, {
                'method': 'GET',
                'headers': {
                    'Authorization': `Bearer ${api_token}`
                }
            });
            if (!resp.ok) {
                let err = JSON.parse(await resp.text()).errors[0].message;
                logger.error(`${err}`);
                fullPageError = true;
                fullPageErrorTitle = t('org.apierror.loadroles');
                fullPageErrorSubtitle = t('org.apierror.' + err);
                return;
            }
            roles = JSON.parse(await resp.text());
        } catch (e) {
            logger.error(`${e}`);
            fullPageError = true;
            fullPageErrorTitle = t('org.apierror.loadroles');
            fullPageErrorSubtitle = t('org.apierror.' + `${e}`.replaceAll('.', ''));
            return;
        }
    })
</script>

{#if fullPageError}
    <FullPageError title="{fullPageErrorTitle}" subtitle="{fullPageErrorSubtitle}"/>
{:else}
    <!-- BREAKING THE LAYOUT! -->

    <!-- Sidenav :O -->
    <OrgWrapper selected="roles" orgid="{orgid}">
        <div class="w-full">
            <!-- Top bar -->
            <h1 class="align-middle inline mt-10 font-semibold text-2xl">{t('org.roles_title')}</h1>
            <button on:click={() => {window.location.href = `/org/${orgid}/roles/add`}} class="align-middle inline w-20 h-31 float-right dark:bg-purple-700 rounded font-bold text-sm p-2 w-25 border-2 dark:border-purple-600 border-purple-700 bg-purple-200">{t('org.roles_cta')}</button>

            <!-- Infobox -->
            <div class="mt-5 p-4 bg-purple-800/20 text-sm rounded">
                <span>{t('org.roles_bar')}</span>
                <a class="inline text-purple-600 hover:text-purple-700 transition font-semibold"
                   href="/docs/roles">{t('org.guide')}</a>
            </div>

            <!-- Table -->
            <!-- roles.data.length === 0 -->
            {#if roles.data.length === 0}
                <div class="mt-5">
                    <h2 class="text-center text-xl font-semibold">{t('org.noroles')}</h2>
                    <h3 class="text-center text-md">{t('org.noroles_cta')}</h3>
                </div>
            {:else}
                <div class="mt-5">
                    <table class="rounded w-full bg-white dark:bg-slate-800 text-sm shadow-sm">
                        <tr>
                            <th class="w-1/4 border-b font-semibold p-4 text-slate-900 dark:text-slate-200 text-left">
                                Name
                            </th>
                            <th class="w-1/8 border-b font-semibold p-4 text-slate-900 dark:text-slate-200 text-left">ID
                            </th>
                            <th class="w-1/8 border-b font-semibold p-4 text-slate-900 dark:text-slate-200 text-left">
                                Rules
                            </th>
                            <th class="w-3/4 border-b font-semibold p-4 text-slate-900 dark:text-slate-200 text-left">
                                Description
                            </th>
                            <th class="border-b p-4"></th>
                        </tr>

                        {#each roles.data as role}
                            <tr>
                                <td class="p-4 text-slate-600 dark:text-slate-300 text-left">{role.name}</td>
                                <td class="p-4 text-slate-600 dark:text-slate-300 text-left">{role.id}</td>
                                <td class="p-4 text-slate-600 dark:text-slate-300 text-left">{role.firewall_rules.length}</td>
                                <td class="p-4 text-slate-600 dark:text-slate-300 text-left">{role.description}</td>
                                <td>
                                    <button class="w-16 border p-2 rounded m-2 hover:bg-slate-100 transition dark:hover:bg-slate-700" on:click={() => {
                                        window.location.href = `/org/${orgid}/roles/${role.id}`
                                    }}>
                                        Edit
                                    </button>
                                </td>
                            </tr>
                        {/each}
                    </table>
                </div>
            {/if}
        </div>
    </OrgWrapper>
{/if}