<script lang="ts">
    import WelcomeScreen from "./WelcomeScreen.svelte";
    import { Pane, Splitpanes } from "svelte-splitpanes";
    import { open } from "@tauri-apps/plugin-dialog";
    import { invoke } from "@tauri-apps/api/core";
    import type PdfFile from "../models/PdfFile";
    import ToolbarLeft from "./ToolbarLeft.svelte";
    import FileView from "./FileView.svelte";
    import FileViewState from "../models/FileViewState.svelte";
    import TitleBar from "./TitleBar.svelte";
    import ToolbarRight from "./ToolbarRight.svelte";
    import Footer from "./Footer.svelte";

    const footerHeight: number = 30;
    const titleBarHeight: number = 30;
    let innerHeight: number = $state(1060);

    let fileViewHeight: number = $derived(
        Math.max(innerHeight - footerHeight - titleBarHeight, 0),
    );

    let fStates: FileViewState[] = $state([]);
    let fState: FileViewState | undefined = $state();

    initialLoadAllFiles();

    function initialLoadAllFiles() {
        invoke<PdfFile[]>("get_all_files")
            .then((result_list) => {
                createFileStates(result_list);
                fState = fStates[0];
            })
            .catch((error) => {
                console.error("File retrieval failed: " + error);
            });
    }

    function createFileStates(files: PdfFile[]) {
        for (let file of files) {
            let fState = fStates.find((state) => state.file.id === file.id);
            if (fState) {
                continue;
            }
            fState = new FileViewState(file);
            fStates.push(fState);
        }
    }

    async function upload() {
        let file_path = await open({
            multiple: false,
            directory: false,
            filters: [{ name: "pdf", extensions: ["pdf"] }],
        });
        if (file_path === null || Array.isArray(file_path)) {
            return;
        }

        let uploadedId = await invoke<string>("upload", {
            path: file_path,
        }).catch((error) => {
            console.error("File upload failed with: " + error);
        });
        if (!uploadedId) return;

        let allFiles = await invoke<PdfFile[]>("get_all_files").catch(
            (error) => {
                console.error("Fetch all files failed with: " + error);
            },
        );
        if (!allFiles) return;

        createFileStates(allFiles);
        fState = fStates.find((state) => state.file.id === uploadedId);
    }

    function closeFile(stateToClose: FileViewState) {
        invoke("close_file", { id: stateToClose.file.id })
            .then((_) => {
                fStates = fStates.filter(
                    (state) => state.file.id !== stateToClose.file.id,
                );
                if (stateToClose.file.id === fState?.file.id) {
                    fState = fStates[0];
                }
            })
            .catch((err) => console.error(err));
    }
</script>

<svelte:window bind:innerHeight />
<main style="height: {innerHeight}px; overflow: hidden;">
    <div style="height: {titleBarHeight}px; z-index: 100; position: relative;">
        <TitleBar
            {fStates}
            {fState}
            closeTab={closeFile}
            openTab={upload}
            selectTab={(state) => (fState = state)}
        ></TitleBar>
    </div>
    <div class="fileview_container" style="height: {fileViewHeight}px">
        <Splitpanes theme="forge-movable" dblClickSplitter={false}>
            <Pane size={2.5} minSize={1.5} maxSize={4}>
                <ToolbarLeft {fState}></ToolbarLeft>
            </Pane>
            <Pane>
                {#if fState}
                    <FileView {fState} height={fileViewHeight}></FileView>
                {:else}
                    <WelcomeScreen {upload}></WelcomeScreen>
                {/if}
            </Pane>

            <Pane size={2.5} minSize={1.5} maxSize={4}>
                <ToolbarRight {fState}></ToolbarRight>
            </Pane>
        </Splitpanes>
    </div>
    <Footer {fState} {footerHeight}></Footer>
</main>

<style global>
    /* Resiable layout */
    :global(.splitpanes.forge-movable) :global(.splitpanes__pane) {
        background-color: var(--background-color);
    }

    :global(.splitpanes.forge-movable) :global(.splitpanes__splitter) {
        background-color: var(--boundary-color);
        box-sizing: border-box;
        position: relative;
        flex-shrink: 0;
    }

    :global(.splitpanes.forge-movable) :global(.splitpanes__splitter:before),
    :global(.splitpanes.forge-movable) :global(.splitpanes__splitter:after) {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        display: none;
        background-color: var(--accent-color);
        transition: background-color 0.3s;
    }

    :global(.splitpanes.forge-movable)
        :global(.splitpanes__splitter:hover:before),
    :global(.splitpanes.forge-movable)
        :global(.splitpanes__splitter:hover:after) {
        background-color: var(--boundary-color);
    }

    :global(.splitpanes.forge-movable)
        :global(.splitpanes__splitter:first-child) {
        cursor: auto;
    }

    :global(.forge-movable.splitpanes)
        :global(.splitpanes)
        :global(.splitpanes__splitter) {
        z-index: 1;
    }

    :global(.forge-movable.splitpanes--vertical)
        > :global(.splitpanes__splitter),
    :global(.forge-movable)
        :global(.splitpanes--vertical)
        > :global(.splitpanes__splitter) {
        width: 2px;
        border-left: 1px solid var(--boundary-color);
        cursor: col-resize;
    }

    :global(.forge-movable.splitpanes--vertical)
        > :global(.splitpanes__splitter:before),
    :global(.forge-movable.splitpanes--vertical)
        > :global(.splitpanes__splitter:after),
    :global(.forge-movable)
        :global(.splitpanes--vertical)
        > :global(.splitpanes__splitter:before),
    :global(.forge-movable)
        :global(.splitpanes--vertical)
        > :global(.splitpanes__splitter:after) {
        transform: translateY(-50%);
        width: 1px;
        height: 40px;
    }

    :global(.forge-movable.splitpanes--vertical)
        > :global(.splitpanes__splitter:before),
    :global(.forge-movable)
        :global(.splitpanes--vertical)
        > :global(.splitpanes__splitter:before) {
        margin-left: -2px;
    }

    :global(.forge-movable.splitpanes--vertical)
        > :global(.splitpanes__splitter:after),
    :global(.forge-movable)
        :global(.splitpanes--vertical)
        > :global(.splitpanes__splitter:after) {
        margin-left: 1px;
    }

    :global(.forge-movable.splitpanes--horizontal)
        > :global(.splitpanes__splitter),
    :global(.forge-movable)
        :global(.splitpanes--horizontal)
        > :global(.splitpanes__splitter) {
        height: 2px;
        border-top: 1px solid var(--boundary-color);
        cursor: row-resize;
    }

    :global(.forge-movable.splitpanes--horizontal)
        > :global(.splitpanes__splitter:before),
    :global(.forge-movable.splitpanes--horizontal)
        > :global(.splitpanes__splitter:after),
    :global(.forge-movable)
        :global(.splitpanes--horizontal)
        > :global(.splitpanes__splitter:before),
    :global(.forge-movable)
        :global(.splitpanes--horizontal)
        > :global(.splitpanes__splitter:after) {
        transform: translateX(-50%);
        width: 40px;
        height: 3px;
    }

    :global(.forge-movable.splitpanes--horizontal)
        > :global(.splitpanes__splitter:before),
    :global(.forge-movable)
        :global(.splitpanes--horizontal)
        > :global(.splitpanes__splitter:before) {
        margin-top: -2px;
    }

    :global(.forge-movable.splitpanes--horizontal)
        > :global(.splitpanes__splitter:after),
    :global(.forge-movable)
        :global(.splitpanes--horizontal)
        > :global(.splitpanes__splitter:after) {
        margin-top: 1px;
    }

    /* Fixed layout */
    :global(.splitpanes.forge-fixed) :global(.splitpanes__pane) {
        background-color: var(--background-color);
    }

    :global(.splitpanes.forge-fixed) :global(.splitpanes__splitter) {
        background-color: var(--boundary-color);
        position: relative;
    }

    :global(div.splitpanes--horizontal.splitpanes--dragging) {
        cursor: row-resize;
    }

    :global(div.splitpanes--vertical.splitpanes--dragging) {
        cursor: col-resize;
    }

    :global(.splitpanes) {
        display: flex;
        width: 100%;
        height: 100%;
    }

    :global(.splitpanes--vertical) {
        flex-direction: row;
    }

    :global(.splitpanes--horizontal) {
        flex-direction: column;
    }

    :global(.splitpanes--dragging) :global(*) {
        user-select: none;
    }

    :global(.splitpanes__pane) {
        width: 100%;
        height: 100%;
        overflow: hidden;
        /** Add also a direct child selector, for dealing with specifity of nested splitpanes transition.
          This issue was happening in the examples on nested splitpanes, vertical inside horizontal.
          I think it's better to keep also the previous CSS selector for (potential) old browser compatibility.
        */
    }

    :global(.splitpanes--vertical) :global(.splitpanes__pane) {
        transition: width 0.2s ease-out;
    }

    :global(.splitpanes--horizontal) :global(.splitpanes__pane) {
        transition: height 0.2s ease-out;
    }

    :global(.splitpanes--vertical) > :global(.splitpanes__pane) {
        transition: width 0.2s ease-out;
    }

    :global(.splitpanes--horizontal) > :global(.splitpanes__pane) {
        transition: height 0.2s ease-out;
    }

    :global(.splitpanes--dragging) :global(.splitpanes__pane) {
        transition: none;
        pointer-events: none;
    }

    :global(.splitpanes--freeze) :global(.splitpanes__pane) {
        transition: none;
    }

    :global(.splitpanes__splitter) {
        touch-action: none;
    }

    :global(.splitpanes--vertical) > :global(.splitpanes__splitter) {
        min-width: 1px;
    }

    :global(.splitpanes--horizontal) > :global(.splitpanes__splitter) {
        min-height: 1px;
    }
</style>
