// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

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

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

  public static drawLine(
    pointA: cc.Vec2,
    pointB: cc.Vec2,
    color: cc.Color = cc.Color.WHITE
  ) {
    if (this._graphic == null) {
      this._graphic = new cc.Node().addComponent(cc.Graphics);
      this._graphic.node.parent = cc.Canvas.instance.node.parent;
      this._graphic.node.opacity = 0;
      this._graphic.strokeColor = color;
      this._graphic.moveTo(pointA.x, pointA.y);
      this._graphic.lineTo(pointB.x, pointB.y);
      this._graphic.stroke();
    }
  }

  public static drawLineOnY(yValue: number, color: cc.Color = cc.Color.WHITE) {
    if (this._graphic == null) {
      this._graphic = new cc.Node().addComponent(cc.Graphics);
      this._graphic.node.parent = cc.Canvas.instance.node.parent;
      this._graphic.strokeColor = color;
      this._graphic.moveTo(0, yValue);
      this._graphic.lineTo(cc.view.getDesignResolutionSize().width, yValue);
      this._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]);
    }
  }
}
