///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2002-2025, Open Design Alliance (the "Alliance").
// All rights reserved.
//
// This software and its documentation and related materials are owned by
// the Alliance. The software may only be incorporated into application
// programs owned by members of the Alliance, subject to a signed
// Membership Agreement and Supplemental Software License Agreement with the
// Alliance. The structure and organization of this software are the valuable
// trade secrets of the Alliance and its suppliers. The software is also
// protected by copyright law and international treaty provisions. Application
// programs incorporating this software must include the following statement
// with their copyright notices:
//
//   This application incorporates Open Design Alliance software pursuant to a
//   license agreement with Open Design Alliance.
//   Open Design Alliance Copyright (C) 2002-2025 by Open Design Alliance.
//   All rights reserved.
//
// By use of this software, its documentation or related materials, you
// acknowledge and accept the above terms.
///////////////////////////////////////////////////////////////////////////////

import Konva from "konva";
import { IMarkupArrow, IMarkupArrowParams } from "../IMarkupArrow";
import { IWorldTransform } from "../IWorldTransform";
import { WorldTransform } from "../WorldTransform";

export class KonvaArrow implements IMarkupArrow {
  private _ref: Konva.Arrow;
  private _worldTransformer: IWorldTransform;

  constructor(params: IMarkupArrowParams, ref = null, worldTransformer = new WorldTransform()) {
    this._worldTransformer = worldTransformer;

    if (ref) {
      this._ref = ref;
      const wcsStart = this._ref.getAttr("wcsStart");
      const wcsEnd = this._ref.getAttr("wcsEnd");
      if (!wcsStart)
        this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld({ x: ref.points()[0], y: ref.points()[1] }));
      if (!wcsEnd)
        this._ref.setAttr("wcsEnd", this._worldTransformer.screenToWorld({ x: ref.points()[2], y: ref.points()[3] }));
      return;
    }

    if (!params) params = {};
    if (!params.start) params.start = { x: 0, y: 0 };
    if (!params.end) params.end = { x: 100, y: 100 };

    this._ref = new Konva.Arrow({
      stroke: params.color ?? "#ff0000",
      fill: params.color ?? "#ff0000",
      strokeWidth: 4,
      globalCompositeOperation: "source-over",
      lineCap: "round",
      lineJoin: "round",
      points: [params.start.x, params.start.y, params.end.x, params.end.y],
      draggable: true,
      strokeScaleEnabled: false,
    });

    this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld({ x: params.start.x, y: params.start.y }));
    this._ref.setAttr("wcsEnd", this._worldTransformer.screenToWorld({ x: params.end.x, y: params.end.y }));

    this._ref.on("transformend", (e) => {
      const attrs = e.target.attrs;
      if (attrs.rotation !== this._ref.rotation()) this._ref.rotation(attrs.rotation);

      const points = this._ref.points();
      const absoluteTransform = this._ref.getAbsoluteTransform();
      const transformStart = absoluteTransform.point({ x: points[0], y: points[1] });
      const transformEnd = absoluteTransform.point({ x: points[2], y: points[3] });
      this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld(transformStart));
      this._ref.setAttr("wcsEnd", this._worldTransformer.screenToWorld(transformEnd));
    });

    this._ref.on("dragend", (e) => {
      const points = this._ref.points();
      const absoluteTransform = e.target.getAbsoluteTransform();
      const transformStart = absoluteTransform.point({ x: points[0], y: points[1] });
      const transformEnd = absoluteTransform.point({ x: points[2], y: points[3] });
      this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld(transformStart));
      this._ref.setAttr("wcsEnd", this._worldTransformer.screenToWorld(transformEnd));
    });

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

  ref() {
    return this._ref;
  }

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

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

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

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

  setColor(hex: string): void {
    this._ref.stroke(hex);
    this._ref.fill(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;
  }

  getPoints(): { x: number; y: number }[] {
    const points = this._ref.points();
    return [
      { x: points[0], y: points[1] },
      { x: points[2], y: points[3] },
    ];
  }

  setPoints(points: { x: number; y: number }[]): void {
    if (points.length === 2) {
      this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld({ x: points[0].x, y: points[0].y }));
      this._ref.setAttr("wcsEnd", this._worldTransformer.screenToWorld({ x: points[1].x, y: points[1].y }));
      this._ref.points([points[0].x, points[0].y, points[1].x, points[1].y]);
    }
  }

  getStartPoint(): { x: number; y: number } {
    const points = this._ref.points();
    return { x: points[0], y: points[1] };
  }

  setStartPoint(x: number, y: number): void {
    const points = this._ref.points();
    this._ref.points([x, y, points[2], points[3]]);
    this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld({ x, y }));
  }

  getEndPoint(): { x: number; y: number } {
    const points = this._ref.points();
    return { x: points[2], y: points[3] };
  }

  setEndPoint(x: number, y: number): void {
    const points = this._ref.points();
    this._ref.points([points[0], points[1], x, y]);
    this._ref.setAttr("wcsEnd", this._worldTransformer.screenToWorld({ x, y }));
  }

  updateScreenCoordinates(): void {
    let screenStartPoint = this._worldTransformer.worldToScreen(this._ref.getAttr("wcsStart"));
    let screenEndPoint = this._worldTransformer.worldToScreen(this._ref.getAttr("wcsEnd"));

    let invert = this._ref.getAbsoluteTransform().copy();
    invert = invert.invert();
    const startPoint = invert.point({ x: screenStartPoint.x, y: screenStartPoint.y });
    const endPoint = invert.point({ x: screenEndPoint.x, y: screenEndPoint.y });

    this._ref.points([startPoint.x, startPoint.y, endPoint.x, endPoint.y]);
  }
}
