///////////////////////////////////////////////////////////////////////////////
// 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 { IMarkupCloud, IMarkupCloudParams } from "../IMarkupCloud";
import { IWorldTransform } from "../IWorldTransform";
import { WorldTransform } from "../WorldTransform";

export class KonvaCloud implements IMarkupCloud {
  private _ref: Konva.Shape;
  private _worldTransformer: IWorldTransform;

  constructor(params: IMarkupCloudParams, 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.x(), y: ref.y() }));
      }
      if (!wcsEnd) {
        const rightBottomPoint = { x: ref.x() + ref.width(), y: ref.y() + ref.height() };
        this._ref.setAttr(
          "wcsEnd",
          this._worldTransformer.screenToWorld({ x: rightBottomPoint.x, y: rightBottomPoint.y })
        );
      }
      return;
    }

    if (!params) params = {};
    if (!params.position) params.position = { x: 0, y: 0 };
    if (params.position2) {
      params.width = params.position.x - params.position2.x;
      params.height = params.position.y - params.position2.y;
    } else {
      if (!params.width || !params.height) {
        params.position2 = { x: 200, y: 200 };
        params.width = 200;
        params.height = 200;
      } else {
        params.position2 = { x: params.position.x + params.width, y: params.position.y + params.height };
      }
    }

    const ARC_RADIUS = 16;

    this._ref = new Konva.Shape({
      x: params.position.x,
      y: params.position.y,
      width: params.width ?? 200,
      height: params.height ?? 200,
      stroke: params.color ?? "#ff0000",
      strokeWidth: params.lineWidth ?? 4,
      draggable: true,
      strokeScaleEnabled: false,
      globalCompositeOperation: "source-over",
      sceneFunc: (context, shape) => {
        function calculateMidpoint(position, width, height) {
          const midX = position.x + width / 2;
          const midY = position.y + height / 2;
          return { x: midX, y: midY };
        }

        const points = [
          { x: 0, y: 0 },
          { x: 0 + this._ref.width(), y: 0 },
          { x: 0 + this._ref.width(), y: 0 + this._ref.height() },
          { x: 0, y: 0 + this._ref.height() },
          { x: 0, y: 0 },
        ];

        const midPoint = calculateMidpoint({ x: 0, y: 0 }, this._ref.width(), this._ref.height());

        const baseArcLength = 30;
        context.beginPath();
        for (let iPoint = 0; iPoint < points.length - 1; iPoint++) {
          let approxArcLength = baseArcLength;
          const dx = points[iPoint + 1].x - points[iPoint].x;
          const dy = points[iPoint + 1].y - points[iPoint].y;
          const length = Math.sqrt(dx * dx + dy * dy);

          const arcCount = Math.floor(length / approxArcLength);
          const lengthMod = length % approxArcLength;
          approxArcLength = baseArcLength + arcCount / lengthMod;

          let pX = points[iPoint].x + dx / arcCount / 2;
          let pY = points[iPoint].y + dy / arcCount / 2;
          const pEndX = points[iPoint + 1].x;
          const pEndY = points[iPoint + 1].y;
          const endAngle = Math.atan((pEndY - pY) / (pEndX - pX));
          const startAngle = endAngle + Math.PI;
          const counterClockwise = pX > midPoint.x && pY > midPoint.y;
          for (let iArc = 0; iArc < arcCount; iArc++) {
            if (counterClockwise) {
              context.arc(pX, pY, ARC_RADIUS, endAngle, startAngle);
            } else {
              context.arc(pX, pY, ARC_RADIUS, startAngle, endAngle);
            }

            pX += dx / arcCount;
            pY += dy / arcCount;
          }
        }

        context.closePath();
        // (!) Konva specific method, it is very important
        // it will apply are required styles
        context.fillStrokeShape(shape);
      },
    });

    this._ref.className = "Cloud";

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

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

      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 = 100;
      const minHeight = 100;

      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.on("transformend", (e) => {
      const attrs = e.target.attrs;
      if (attrs.rotation !== this._ref.rotation()) this._ref.rotation(attrs.rotation);

      const absoluteTransform = this._ref.getStage().getAbsoluteTransform();
      const position = absoluteTransform.point({ x: this._ref.x(), y: this._ref.y() });
      this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld(position));
      this._ref.setAttr(
        "wcsEnd",
        this._worldTransformer.screenToWorld({ x: position.x + this._ref.width(), y: position.y + this._ref.height() })
      );
    });

    this._ref.on("dragend", (e) => {
      const absoluteTransform = this._ref.getStage().getAbsoluteTransform();
      const position = absoluteTransform.point({ x: this._ref.x(), y: this._ref.y() });
      this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld(position));
      this._ref.setAttr(
        "wcsEnd",
        this._worldTransformer.screenToWorld({ x: position.x + this._ref.width(), y: position.y + this._ref.height() })
      );
    });

    this._ref.getSelfRect = () => {
      return {
        x: 0 - ARC_RADIUS,
        y: 0 - ARC_RADIUS,
        width: this._ref.width() + 2 * ARC_RADIUS,
        height: this._ref.height() + 2 * ARC_RADIUS,
      };
    };

    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 "Cloud";
  }

  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;
  }

  getPosition() {
    return this._ref.position();
  }

  setPosition(x: number, y: number): void {
    this._ref.position({ x, y });
    this._ref.setAttr("wcsStart", this._worldTransformer.screenToWorld({ x, y }));
  }

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

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

    const rightLowerPoint = { x: this._ref.x() + w, y: this._ref.y() + this._ref.height() };
    const wcsRightLowerPoint = this._worldTransformer.screenToWorld(rightLowerPoint);
    this._ref.setAttr("wcsEnd", wcsRightLowerPoint);
  }

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

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

    const rightLowerPoint = { x: this._ref.x() + this._ref.width(), y: this._ref.y() + h };
    const wcsRightLowerPoint = this._worldTransformer.screenToWorld(rightLowerPoint);
    this._ref.setAttr("wcsEnd", wcsRightLowerPoint);
  }

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

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

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

    let invert = this._ref.getStage().getAbsoluteTransform().copy();
    invert = invert.invert();
    const positionStart = invert.point(screenPositionStart);
    const positionEnd = invert.point(screenPositionEnd);

    this._ref.position({ x: positionStart.x, y: positionStart.y });
    this._ref.width(Math.abs(positionEnd.x - positionStart.x));
    this._ref.height(Math.abs(positionEnd.y - positionStart.y));
  }
}
