<template>
    <div class="content-l">
        <h1>Account Settings</h1>
        <div class="col-3">
            <div class="tile-m">
                <h3>User ID</h3>
                <p>{{userId}}</p>
            </div>
            <div class="tile-m">
                <h3>E-Mail</h3>
                <p>andreas.j.dinauer@gmail.com</p>
            </div>
            <div class="tile-m">
                <h3>Password</h3>
                <p>************</p>
            </div>
        </div>
        <h1>Access Tokens</h1>
        <div v-if="tokens">
            <p v-if="tokens.length === 0" class="tile-m">No tokens created yet.</p>
            <UiTable v-else columns="auto 1fr auto auto">
                <HeaderRow>
                    <HeaderCell>Name</HeaderCell>
                    <HeaderCell>Created At</HeaderCell>
                    <HeaderCell>Expires At</HeaderCell>
                    <HeaderCell></HeaderCell>
                </HeaderRow>
                <ContentRow v-for="token in tokens">
                    <ContentCell>{{ token.name }}</ContentCell>
                    <ContentCell>{{ dayjs(token.createdAt).format("DD.MM.YYYY") }}</ContentCell>
                    <ContentCell>{{ dayjs(token.expiresAt).format("DD.MM.YYYY") }}</ContentCell>
                    <ContentCell style="padding: 0.25rem"><UiButton @click="del(token)" icon="delete"></UiButton></ContentCell>
                </ContentRow>
            </UiTable>
        </div>
        <div>
            <UiButton @click="usePopup().open(new Popup(TokenCreationComponent, { size: PopupSize.MEDIUM, heading: 'Create Token', callback: (token: Token) => { tokens?.push(token) } }))">Create</UiButton>
        </div>
    </div>
</template>

<script setup lang="ts">
import TokenCreationComponent from "~/components/settings/token/TokenCreationComponent.vue";
import {Popup, PopupSize, usePopup} from "~/components/ui/popup/Popup";
import {Token} from "~/auth/Token";
import HeaderCell from "~/components/ui/table/HeaderCell.vue";
import HeaderRow from "~/components/ui/table/HeaderRow.vue";
import ContentRow from "~/components/ui/table/ContentRow.vue";
import ContentCell from "~/components/ui/table/ContentCell.vue";
import dayjs from "dayjs";
import {jwtDecode} from "jwt-decode";

const userId = (jwtDecode(useCookie<string>("identity").value) as any).upn;

const tokens: Ref<Token[] | undefined> = ref(undefined);
onMounted(() => {
    Token.get((_tokens: Token[]) => {
        tokens.value = _tokens;
    })
})

function del(token: Token)
{
    Token.delete(token.id, () => {
        if (tokens.value)
        {
            tokens.value = tokens.value.filter(item => item.id !== token.id);
        }
    })
}
</script>

<style scoped>

</style>