import * as GC from "@mescius/spread-sheets";
import {SharedDoc} from "@mescius/js-collaboration-ot-client";
import React, {useState, useRef, useMemo, useEffect} from 'react';
import {CheckOutlined, FileExcelOutlined, SyncOutlined} from "@ant-design/icons";
import {IChangeSet, type} from "@mescius/spread-sheets-collaboration-client";

interface HeadProps {
    workbook: GC.Spread.Sheets.Workbook;
    doc: SharedDoc<any, IChangeSet>
}

enum ConnectStatus {
    Syncing,
    Success
}

export const useBind = (props: HeadProps) => {
    const { workbook, doc }  = props;
    const [status, setStatus] = useState<ConnectStatus>(ConnectStatus.Success);
    const successTimerRef = useRef<any>();
    const bind = async (workbook: GC.Spread.Sheets.Workbook, doc: SharedDoc<any, IChangeSet>) => {
        (workbook as any).collaboration.registerCollaborationType(type);
        // sync-status
        try {
            await doc.subscribe();
            workbook.collaboration.fromSnapshot(doc.data);
            // collaboration not support undo
            workbook.options.allowUndo = false;
            workbook.collaboration.onChangeSet(async (changeSet: IChangeSet) => {
                if (changeSet.ops.length > 0) {
                    beginSync();
                    await doc.submitOp(changeSet, { source: doc.connection.id });
                    endSync();
                }
            });
    
            doc.on('op', (changeSet: IChangeSet, source: any) => {
                if (source === doc.connection.id) {
                    return;
                }
                if (changeSet.ops.length > 0) {
                    try {
                        workbook.collaboration.applyChangeSet(changeSet);
                    } catch (e) {
                        console.error(e);
                    }
                }
            });
        } catch (error) {
            return console.error(error);
        }
    };
    const beginSync = () => {
        setStatus(ConnectStatus.Syncing);
        clearTimeout(successTimerRef.current);
    };
    const endSync = () => {
        clearTimeout(successTimerRef.current);
        // Leave more time to show syncing, so add setTimeout
        successTimerRef.current = setTimeout(() => {
            setStatus(ConnectStatus.Success);
        }, 300);
    };
    useEffect(() => {
        bind(workbook, doc);
    }, []);
    return status;
}
export const Header = (props: HeadProps) => {

    const { workbook, doc } = props;
    const status = useBind({ workbook, doc });
    const text = useMemo(() => {
        if (status === ConnectStatus.Success) {
            return 'Saved';
        } else if (status === ConnectStatus.Syncing) {
            return 'Syncing...';
        }
    }, [status])

    const icon = useMemo(() => {
        if (status === ConnectStatus.Success) {
            return <CheckOutlined style={{ fontSize: "16px", color: 'green' }} />;
        } else if (status === ConnectStatus.Syncing) {
            return <SyncOutlined style={{ fontSize: "16px" }} />;
        }
    }, [status])

    return (
        <>
            <FileExcelOutlined style={{ fontSize: "24px", color: 'green' }}/>
            <div style={{ fontSize: '18px', margin: "0 12px" }}>Workbook</div>
            {icon}
            <div style={{ fontSize: '16px', margin: "0 12px" }}>{text}</div>
        </>

    )
}

