const { ccclass, property } = cc._decorator;

@ccclass
export default class MagnifyingMirror extends cc.Component {
  @property(cc.Node)
  mirrorCameraNode: cc.Node = null;
  @property(cc.Node)
  tempCameraSpriteNode: cc.Node = null;
  viewSize: cc.Size = null;
  touchStartPos: cc.Vec2 = null;
  mirrorOriginPos: cc.Vec2 = null;

  onLoad() {
    this.viewSize = cc.view.getVisibleSize();
    this.mirrorCameraNode.setPosition(this.node.getPosition());

    this.node.on(cc.Node.EventType.TOUCH_START, this.touchStartEvent, this);
    this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveEvent, this);
  }
  protected start(): void {
    this.initCamera();
  }

  touchStartEvent(event) {
    this.touchStartPos = event.getLocation();
    this.mirrorOriginPos = this.node.getPosition();
  }

  touchMoveEvent(event) {
    let touchPos: cc.Vec2 = event.getLocation();
    let pos = this.mirrorOriginPos.add(touchPos.subtract(this.touchStartPos))

    this.node.setPosition(pos);
    this.mirrorCameraNode.setPosition(pos);
  }
  initCamera() {

    const camera = this.mirrorCameraNode.getComponent(cc.Camera);
    // 先保存当前的渲染状态
    const originalEnabled = camera.enabled;

    // 临时禁用相机
    camera.enabled = false;

    let visibleRect = cc.view.getVisibleSize();
    let texture = new cc.RenderTexture();
    texture.initWithSize(visibleRect.width, visibleRect.height, 999);

    let spriteFrame = new cc.SpriteFrame();
    spriteFrame.setTexture(texture);

    // 设置渲染目标
    camera.targetTexture = texture;
    camera.clearFlags = cc.Camera.ClearFlags.ALL;
    camera.backgroundColor = cc.color(0, 0, 0, 0);

    // 重新启用相机
    camera.enabled = originalEnabled;

    this.tempCameraSpriteNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
    this.tempCameraSpriteNode.scaleY = -1;
  }
}
