import {Client, Connection} from "@mescius/js-collaboration-client";
import * as OT from "@mescius/js-collaboration-ot-client";
import { type } from './type'
import {SharedDoc} from "@mescius/js-collaboration-ot-client";
import {Presence} from "@mescius/js-collaboration-presence-client";
import {clearUserPresence, IPresence, IUser} from "./presence";
import Konva from "konva";
import {bindKonvaAndPresence} from "./bind";

OT.TypesManager.register(type);

const userCache = new Map<string, { doc: SharedDoc, stage: Konva.Stage, conn: Connection, userHostId: string, hostId: string }>();
let isCreated = false;
export async function createBindKonva (hostId: string, userHostId: string, user: IUser): Promise<void> {
    const div = document.getElementById(hostId) as HTMLDivElement;
    const stage = new Konva.Stage({
        container: div,
        width: div.clientWidth,
        height: div.clientHeight,
    });
    const conn = new Client().connect('room1');
    const doc = new OT.SharedDoc(conn);
    const presence = new Presence<IPresence>(conn);
    userCache.set(user.id, { doc, stage, conn, userHostId, hostId });
    await doc.fetch();
    if (!doc.type && isCreated === false) {
        isCreated = true;
        await doc.create([], type.uri, {});
        bindKonvaAndPresence(stage, doc, presence, user, userHostId, hostId);
    } else {
        bindKonvaAndPresence(stage, doc, presence, user, userHostId, hostId);
    }
}

export function removeBindKonva (userId: string) {
    const instance = userCache.get(userId);
    if (instance) {
        const { doc, stage, conn, userHostId, hostId } = instance;
        conn.close();
        doc.destroy();
        stage.destroy();
        clearUserPresence(userHostId);
    }
}

export function refreshKonva () {
    userCache.forEach(value => {
        const { stage, hostId } = value;
        const divDom = document.getElementById(hostId);
        stage.width(divDom.clientWidth);
        stage.height(divDom.clientHeight);
    })
}
