import { addImage } from "./utils";
import Ball from "./Ball";
import World from "./World";

export default class Gun extends egret.Sprite {
    _root: egret.DisplayObjectContainer;
    _world: World;
    _line: egret.Bitmap;
    _gun: egret.Bitmap;
    constructor(root: egret.DisplayObjectContainer, world: World) {
        super();
        this._root = root;
        this._world = world;
        this.initUI();
    }

    fire() {
        egret.Tween.get(this._gun)
            .to({ scaleY: 0.6 }, 100)
            .to({ scaleY: 1 }, 100);
        this.addBall();
    }

    addBall() {
        const ball = new Ball();
        ball.init();
        this._world.addBody(ball);
        this._root.addChild(ball.skin);
    }

    enable() {
        this.hideLine();
        this.stage.once(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);
    }

    onTouchBegin() {
        this.showLine();
        this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this);
        this.stage.once(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchEnd(): any {
        this.hideLine();
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this);
        // this.fire();
    }

    onTouchMove(e: egret.TouchEvent) {
        const point = new egret.Point(e.stageX, e.stageY)
        var pos = new egret.Point(point.x - this.x, point.y - this.y);
        var r: number = -Math.atan2(pos.x, pos.y) * 180 / Math.PI;
        this._gun.rotation = r;
        this._line.rotation = r;
    }

    private initUI() {
        const line = addImage('line_png', this);
        line.anchorOffsetX = line.width / 2;
        const gun = addImage('gun_png', this);
        gun.anchorOffsetX = gun.width / 2;
        const numBg = addImage('numBg_png', this);
        numBg.anchorOffsetX = numBg.width >> 1;
        numBg.anchorOffsetY = numBg.height >> 1;
        this._line = line;
        this._gun = gun;
    }

    showLine() {
        this.addChildAt(this._line, 0);
    }

    hideLine() {
        this.removeChild(this._line)
    }
}