const { ccclass, property } = cc._decorator;

@ccclass
export default class Drawer extends cc.Component {
  private static _graphic: cc.Graphics = null;
  private static instance: Drawer = null;

  protected onLoad(): void {
    if (Drawer.instance == null) {
      Drawer.instance = this;
      cc.game.addPersistRootNode(this.node);
    }
  }

  public static clear() {
    if (Drawer._graphic == null) {
      Drawer._graphic.clear();
    }
  }

  public static drawLine(
    pointA: cc.Vec2,
    pointB: cc.Vec2,
    color: cc.Color = cc.Color.WHITE
  ) {
    if (Drawer._graphic == null) {
      Drawer._graphic = new cc.Node().addComponent(cc.Graphics);
      Drawer._graphic.node.parent = cc.Canvas.instance.node.parent;
    }

    Drawer._graphic.strokeColor = color;
    Drawer._graphic.moveTo(pointA.x, pointA.y);
    Drawer._graphic.lineTo(pointB.x, pointB.y);
    Drawer._graphic.stroke();
  }

  public static drawLineOnY(yValue: number, color: cc.Color = cc.Color.WHITE) {
    if (Drawer._graphic == null) {
      Drawer._graphic = new cc.Node().addComponent(cc.Graphics);
      Drawer._graphic.node.parent = cc.Canvas.instance.node.parent;
      Drawer._graphic.strokeColor = color;
      Drawer._graphic.moveTo(0, yValue);
      Drawer._graphic.lineTo(cc.view.getDesignResolutionSize().width, yValue);
      Drawer._graphic.stroke();
    }
  }

  public static drawRect(rect: cc.Rect) {
    Drawer.drawLine(cc.v2(rect.x, rect.y), cc.v2(rect.x + rect.width, rect.y));
    Drawer.drawLine(cc.v2(rect.x, rect.y), cc.v2(rect.x, rect.y + rect.height));
    Drawer.drawLine(
      cc.v2(rect.x + rect.width, rect.y + rect.height),
      cc.v2(rect.x + rect.width, rect.y)
    );
    Drawer.drawLine(
      cc.v2(rect.x + rect.width, rect.y + rect.height),
      cc.v2(rect.x, rect.y + rect.height)
    );
  }

  public static drawArray(array: Array<cc.Vec2>) {
    for (let i = 1; i < array.length; i++) {
      this.drawLine(array[i - 1], array[i]);
    }
  }
}
