import Konva from "konva";
import { useEffect, useRef } from "react";

export default function KonvaViewer(props: { data: IData }) {
    const ref = useRef<HTMLDivElement>(null);
    const { data } = props;

    useEffect(() => {
        const div = ref.current as HTMLDivElement;
        const stage = new Konva.Stage({
            container: div,
            width: div.clientWidth,
            height: div.clientHeight,
        });

        const layer = new Konva.Layer();
        stage.add(layer);

        fromJSON(stage, data);

        return () => {
            stage.destroy();
        }
    }, [data])

    return (
        <div ref={ref} style={{ height: "100%" }}></div>
    )
}

export interface IOp {
    type: 'addLine' | 'addPoint',
    data: any;
}

export type IBatchOp = IOp[];
export type IData = IOp[];

export function fromJSON(stage: Konva.Stage, data: IData) {
    const layer = stage.getLayers()[0];

    data.forEach((op) => applyOp(layer, op));
}

export function applyOp(layer: Konva.Layer, op: IOp) {
    if (op.type === 'addLine') {
        layer.add(new Konva.Line(op.data));
    } else if (op.type === 'addPoint') {
        const { lineId, x, y } = op.data;
        const line = layer.findOne((c: any) => c.attrs.id === lineId) as Konva.Line;
        line.points(line.points().concat([x, y]));
    }
    layer.batchDraw();
}

export function applyOps(layer: Konva.Layer, ops: IOp[]) {
    ops.forEach(op => applyOp(layer, op));
}