import ContentModel from "./ContentModel.svelte";
import {invoke} from "@tauri-apps/api/core";
import type FileViewState from "./FileViewState.svelte";
import {Mutex} from "async-mutex";

export class PageViewState {
    file_id: string;
    fState: FileViewState;


    display_lock = new Mutex();
    contents: ContentModel | undefined = $state(undefined);
    render: () => void;
    constructor(fState: FileViewState, render: () => void) {
        this.file_id = fState.file.id;
        this.fState = fState;
        this.render = render;
        const num = fState.getCurrentPageNumber();
        if (num) {
            this.load(num);
        }
    }

    private logError(err: string) {
        this.fState.logError(err);
    }


    public async load(page_num: number) {
        this.render();

        invoke<ContentModel>("get_contents", {id: this.file_id, path: "Page" + page_num})
            .then((result) => {
                this.contents = new ContentModel(result.parts);
            })
            .catch(this.logError);
    }

    public async loadImage(display: HTMLCanvasElement) {
        this.display_lock.acquire().then(release => {
                try {
                    let page_num = this.fState.getCurrentPageNumber();
                    if (!page_num) return;
                    this.fState.renderer.render_page(page_num, display)
                } finally {
                    release()
                }
            }
        )
        this.display_lock.release();
    }

    public handleSave(newData: string) {
        let page_num = this.fState.getCurrentPageNumber();
        if (!page_num) return;
        let contents = ContentModel.fromDisplay(newData);
        console.log(contents);
        invoke<ContentModel>("update_contents", {id: this.file_id, path: "Page" + page_num, contents: contents})
            .then((result) => {
                this.contents = undefined;
                this.fState.reload();
            })
            .catch(this.logError);
    }
}