<script lang="ts">
    import {Spinner, Toolbar, ToolbarButton, ToolbarGroup, Tooltip} from "flowbite-svelte";
    import {markdown} from "@codemirror/lang-markdown";
    import CodeMirror from "svelte-codemirror-editor";
    import {pageRepo} from "../../repo/repo.ts";
    import {base64ToBytes} from "../../util.ts";
    import type {Page} from "../../types/page.ts";
    import {materialDark} from '@ddietr/codemirror-themes/material-dark.js'
    import {EditOutline} from "flowbite-svelte-icons";
    import {createEventDispatcher} from "svelte";

    export let pageId: number;
    export let branch: string;

    let dispatcher = createEventDispatcher();

    $: pageFuture = $pageRepo.getPage(pageId, branch).then(getPage);
    let pageContent = "";
    let page: Page | null = null;

    function getPage(value: Page): Page {
        page = value;
        pageContent = new TextDecoder().decode(base64ToBytes(value.content));
        return value;
    }

    function savePage() {
        let message = window.prompt("Commit message:", "Update " + page!.name)
        if (message) {
            $pageRepo.updatePage(pageId, pageContent, page!.sha, message, branch)
        }
    }

    async function deletePage() {
        let message = window.prompt("Commit message:", "Delete " + page!.name)
        if (message) {
            await $pageRepo.deletePage(pageId, message, page!.sha, branch)
            dispatcher("reload")
        }
    }
</script>

{#await pageFuture}
    <Spinner />
{:then p}
    <div>
        <div>
            <Toolbar class="!bg-gray-900">
                <ToolbarGroup slot="end">
                    <ToolbarButton on:click={deletePage}>
                        Delete
                    </ToolbarButton>
                    <ToolbarButton color="primary" on:click={savePage}>
                        Save
                    </ToolbarButton>
                </ToolbarGroup>
            </Toolbar>
        </div>
        <CodeMirror bind:value={pageContent} lang={markdown()} theme={materialDark} />
    </div>
{:catch error}
    <p>{error.message}</p>
{/await}