// tslint:disable:only-arrow-functions
// tslint:disable:no-conditional-assignment
// tslint:disable:prefer-const
// tslint:disable:no-var-keyword
// tslint:disable:no-inferrable-types
import { Vector } from "./Vector";
import { Tween } from "../../tween/Tween";
import Body from "./Body";
export class Circle extends Body {
    public type = "circle";
    public view;
    public radius;

    _num;

    _x = 0;
    _y = 0;

    constructor(radius, view) {
        super();
        this.radius = radius;
        this.view = view;
    }

    get x() {
        return this._x;
    }

    set x(value) {
        if (this._x != value) {
            this._x = value;
            this.view.x = value;
        }
    }

    get y() {
        return this._y;
    }

    set y(value) {
        if (this._y != value) {
            this._y = value;
            this.view.y = value;
        }
    }

    get num() {
        return this._num;
    }

    set num(value) {
        if (this._num != value) {
            this._num = value;
            this.view.txt&&(this.view.txt.text = value+"");
        }
    }

    public shake() {
        this.view.bg.x = 0;
        this.view.bg.y = 0;
        Tween.to(this.view.bg, 1, {
            x: 3,
            y:  3,
            yoyo: 2,
            useFrame: true,
            onComplete: function () {

            }

        })
    }

    collideBall(ball) {
        var deltaX = ball.view.x - this.view.x;
        var deltaY = ball.view.y - this.view.y;
        //碰撞

        if (deltaX * deltaX + deltaY * deltaY < (this.radius + ball.radius)*(this.radius + ball.radius)) {
            var velocity = ball.velocity.clone();
            var deta = Math.floor(velocity.length() / ball.radius)+5    //deta就是插值数量,如为0，则直接取上一帧的法向量
            var speedX = velocity.x / (deta + 1);
            var speedY = velocity.y / (deta + 1);
            for (var i = 0; i <= deta; i++) {
                var normal = this.nearestCollideNormal({ x: ball.view.x - speedX * (i + 1), y: ball.view.y - speedY * (i + 1) }, ball, deta + 1, i + 1)
                if (normal) {
                    return normal
                }
            }
        } else {
            return false
            //提前给出要碰撞的法向量
            // return new Vector(deltaX,deltaY).cross();
        }
    }

    private nearestCollideNormal(position, ball, deta, i) {
        var deltaX = position.x-this.view.x ;
        var deltaY = position.y-this.view.y;
        if (deltaX * deltaX + deltaY * deltaY < (this.radius + ball.radius)*(this.radius + ball.radius)) {
            return false;
        } else {
            //直接更改球的位置为最接近碰撞的位置
            ball.view.x -= ball.velocity.x / deta * i;
            ball.view.y -= ball.velocity.y / deta * i;
            //提前给出要碰撞的法向量
            return new Vector(deltaX, deltaY).cross();
        }
    }

}