import { Pos } from '@/utils/math';
import Konva from 'konva';
import { Transformer as BaseTransformer } from 'konva/lib/shapes/Transformer'
import { Transform } from 'konva/lib/Util';


const MAX_SAFE_INTEGER = 100000000;
export class Transformer extends BaseTransformer {
  __getNodeRect() {const node = this.getNode();
    if (!node) {
        return {
            x: -MAX_SAFE_INTEGER,
            y: -MAX_SAFE_INTEGER,
            width: 0,
            height: 0,
            rotation: 0,
        };
    }
    const totalPoints: Pos[] = [];
    this.nodes().map((node) => {
        const box = node.getClientRect({
            skipTransform: true,
            skipShadow: true,
            skipStroke: this.ignoreStroke(),
        });
        const points = [
            { x: box.x, y: box.y },
            { x: box.x + box.width, y: box.y },
            { x: box.x + box.width, y: box.y + box.height },
            { x: box.x, y: box.y + box.height },
        ];
        const trans = node.getAbsoluteTransform();
        points.forEach(function (point) {
            const transformed = trans.point(point);
            totalPoints.push(transformed);
        });
    });
    const tr = new Transform();
    tr.rotate(-Konva.getAngle(this.rotation()));
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    totalPoints.forEach(function (point) {
        const transformed = tr.point(point);
        if (minX === undefined) {
            minX = maxX = transformed.x;
            minY = maxY = transformed.y;
        }
        minX = Math.min(minX, transformed.x);
        minY = Math.min(minY, transformed.y);
        maxX = Math.max(maxX, transformed.x);
        maxY = Math.max(maxY, transformed.y);
    });
    tr.invert();
    const p = tr.point({ x: minX, y: minY });
    return {
        x: p.x,
        y: p.y,
        width: maxX - minX,
        height: maxY - minY,
        rotation: Konva.getAngle(this.rotation()),
    };
  }
}