import Konva from "konva";
import { IMarkupRectangle, IMarkupRectangleParams } from "../IMarkupRectangle";

export class KonvaRectangle implements IMarkupRectangle {
  private _ref: Konva.Rect;

  constructor(params: IMarkupRectangleParams, ref = null) {
    if (ref) {
      this._ref = ref;
      return;
    }

    if (!params) params = {};
    if (!params.position) params.position = { x: 0, y: 0 };

    this._ref = new Konva.Rect({
      stroke: params.color ?? "#ff0000",
      strokeWidth: params.lineWidth ?? 4,
      globalCompositeOperation: "source-over",
      lineCap: "round",
      lineJoin: "round",
      x: params.position.x,
      y: params.position.y,
      width: params.width ?? 200,
      height: params.height ?? 200,
      draggable: true,
      strokeScaleEnabled: false,
    });

    this._ref.on("transform", (e) => {
      const attrs = e.target.attrs;

      if (attrs.rotation !== this._ref.rotation()) this._ref.rotation(attrs.rotation);

      const scaleByX = Math.abs(attrs.scaleX - 1) > 10e-6;
      const scaleByY = Math.abs(attrs.scaleY - 1) > 10e-6;

      let newWidth = this._ref.width();
      if (scaleByX) newWidth *= attrs.scaleX;
      let newHeight = this._ref.height();
      if (scaleByY) newHeight *= attrs.scaleY;

      const minWidth = 50;
      const minHeight = 50;

      if (newWidth < minWidth) newWidth = minWidth;
      if (newHeight < minHeight) newHeight = minHeight;

      if (scaleByX) {
        this._ref.width(newWidth);
      }

      if (scaleByY) {
        this._ref.height(newHeight);
      }

      this._ref.scale({ x: 1, y: 1 });
    });

    this._ref.id(this._ref._id.toString());
  }

  getPosition(): { x: number; y: number } {
    return this._ref.position();
  }

  getWidth(): number {
    return this._ref.width();
  }

  getHeigth(): number {
    return this._ref.height();
  }

  setWidth(w: number): void {
    this._ref.width(w);
  }

  setHeight(h: number): void {
    this._ref.height(h);
  }

  setPosition(x: number, y: number): void {
    this._ref.setPosition({ x, y });
  }

  ref() {
    return this._ref;
  }

  id(): string {
    return this._ref.id();
  }

  enableMouseEditing(value: boolean): void {
    this._ref.draggable(value);
  }

  type(): string {
    return "Rectangle";
  }

  getColor(): string {
    return this._ref.stroke() as string;
  }

  setColor(hex: string): void {
    this._ref.stroke(hex);
  }

  getRotation(): number {
    return this._ref.rotation();
  }

  setRotation(degrees: number): void {
    this._ref.rotation(degrees);
  }

  getZIndex(): number {
    return this._ref.zIndex();
  }

  setZIndex(zIndex: number): void {
    this._ref.zIndex(zIndex);
  }

  delete(): void {
    this._ref.destroy();
    this._ref = null;
  }

  setLineWidth(size: number): void {
    this._ref.strokeWidth(size);
  }

  getLineWidth(): number {
    return this._ref.strokeWidth();
  }
}
