import '@mescius/spread-sheets-formula-panel';
import "@mescius/spread-sheets-pivot-addon";
import "@mescius/spread-sheets-designer-resources-en";
import * as GC from "@mescius/spread-sheets-designer";
import "@mescius/spread-sheets-collaboration-addon";
import "@mescius/spread-sheets-collaboration";
import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css";
import "@mescius/spread-sheets-designer/styles/gc.spread.sheets.designer.light.min.css";

import * as OT from '@mescius/js-collaboration-ot-client';
import { Presence } from "@mescius/js-collaboration-presence-client";
import { bind, bindPresence, IPresence, IChangeSet, type } from '@mescius/spread-sheets-collaboration-client'
import { useEffect, useRef } from "react";
import { randomColor } from './util';
import { IDoc } from '../../request/doc';
import { IUser } from '../../request/user';
import { connect } from '../../request/req';
import {CustomHeader, PageType} from "../Header";

OT.TypesManager.register(type);

export default function SharedSpreadSheets(props: { doc: IDoc, user: IUser, readonly: boolean }) {
    const ref = useRef<HTMLDivElement>(null);
    const { doc, user } = props;


    useEffect(() => {
        const div = ref.current as HTMLDivElement;
        const conn = connect(doc.id);
        const sharedDoc = new OT.SharedDoc<any, IChangeSet>(conn);
        const presence = new Presence<IPresence>(conn);
        const color = randomColor();

        const designer = new GC.Spread.Sheets.Designer.Designer(div);
        const config = GC.Spread.Sheets.Designer.DefaultConfig;
        delete config.fileMenu;
        designer.setConfig(config);
        const workbook = designer.getWorkbook() as any;
        bind(workbook, sharedDoc);
        bindPresence(workbook, presence, {
            id: user.id,
            name: user.username,
            color,
            permission: {
                mode: props.readonly ? 1 : 0
            }
        });

        return () => {
            sharedDoc.destroy();
            sharedDoc.connection.close();
            designer.destroy();
            workbook.destroy();
        };
    }, [doc.id, user])

    return (
        <CustomHeader type={PageType.Open} doc={doc}>
            <div ref={ref} style={{ width: '100%', height: "100%", border: "1px solid #ccc" }}></div>
        </CustomHeader>
    )
}
