<script lang="ts">
    import { invoke } from "@tauri-apps/api/core";
    import type ContentModel from "../models/ContentModel.svelte";
    import { onMount } from "svelte";
    import * as monaco from "monaco-editor";
    import type FileViewState from "../models/FileViewState.svelte";

    let { fState, height }: { fState: FileViewState; height: number } =
        $props();
    let h = $derived(height);
    let path = $derived(fState.prim?.getFirstJump()?.toString());
    let id = $derived(fState.file.id);
    let contents: ContentModel | undefined = $state(undefined);
    let editorContainer: HTMLElement;
    let editor: monaco.editor.IStandaloneCodeEditor;

    onMount(() => {
        editor = monaco.editor.create(editorContainer, {
            value: "",
            language: "plaintext",
            theme: "vs-dark",
            minimap: { enabled: false },
            scrollBeyondLastLine: false,
            fontSize: 14,
            automaticLayout: true,
        });

        return () => {
            editor.dispose();
        };
    });

    $effect(() => {
        loadContents(path, id);
    });

    function loadContents(path: string | undefined, id: string) {
        if (!path || !id) return;

        invoke<ContentModel>("get_contents", { id, path })
            .then((result) => {
                contents = result;
                if (contents && editor) {
                    let text = "";
                    if (contents.parts.length > 1) {
                        let i = 0;
                        for (let part of contents.parts) {
                            text +=
                                "%----------------% Contents[" +
                                i +
                                "] %--------------%\n\n";
                            for (let line of part) {
                                text += "  " + line + "\n";
                            }
                            text +=
                                "\n%-------------------% EOF %-------------------%\n\n";
                            i++;
                        }
                    } else {
                        text = contents.parts[0].join("\n");
                    }
                    editor.setValue(text);
                }
            })
            .catch((err) => console.error(err));
    }
</script>

<div bind:this={editorContainer} style="height: {h}px; width: 100%;"></div>

<style lang="postcss">
</style>
