<script lang="ts">
    import {Spinner, Toolbar, ToolbarButton, ToolbarGroup, Tooltip} from "flowbite-svelte";
    import {json} from "@codemirror/lang-json";
    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 {createEventDispatcher} from "svelte";
    import MDEMarkdownEditor from "./MDEMarkdownEditor.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>
        {#if page?.name.endsWith("md")}
            <MDEMarkdownEditor bind:value={pageContent} />
        {:else}
            <CodeMirror bind:value={pageContent} lang={json()} theme={materialDark} />
        {/if}
    </div>
{:catch error}
    <p>{error.message}</p>
{/await}