import Global from "./Global";

const { ccclass, property } = cc._decorator;

@ccclass
export default class BallRaycast extends cc.Component {
    private static readonly BALL_RADIUS = 4;
    private radius = 1000;
    private remainLength: number;
    private reflectLength = 100;
    private intervalLength: number = 25;
    private ballWidth: number;

    private refletTimes: number;

    private ctx: cc.Graphics;
    onLoad() {
        this.ctx = this.getComponent(cc.Graphics);
    }

    startRaycast(p1: cc.Vec2, direction: cc.Vec2, ballWidth: number) {
        let localPos = p1;// this.node.convertToNodeSpaceAR(p1);

        this.refletTimes = 0;
        this.ballWidth = ballWidth;
        let p2 = cc.v2(direction).mul(this.radius).add(localPos);
        this.ctx.clear();

        this.remainLength = this.radius;
        this.rayCast(localPos, p2);
    }

    rayCast(p1: cc.Vec2, p2: cc.Vec2) {
        let manager = cc.director.getPhysicsManager();
        let results: cc.PhysicsRayCastResult[] = manager.rayCast(p1, p2, cc.RayCastType.All);
        let result = null;
        for (let i of results) {
            //cc.log('i.collider.tag = ' + i.collider.tag);
            if (i.collider.tag == Global.TAG_WALL) {
                result = i;
                break;
            }
        }

        if (result) {
            p2 = result.point;
        }

        let inVec = p2.sub(p1);
        let lineLength = inVec.mag() - this.ballWidth;
        let pos: cc.Vec2 = cc.v2(this.node.convertToNodeSpaceAR(p1));
        let increment = inVec.normalize().mul(this.intervalLength);
        //只要线段长度还大于每条线段的长度
        for (; lineLength > this.intervalLength; lineLength -= this.intervalLength) {
            //cc.log("add circle");
            pos = pos.add(increment);
            this.ctx.moveTo(pos.x, pos.y)
            this.ctx.circle(pos.x, pos.y, BallRaycast.BALL_RADIUS);
            this.ctx.fill();
        }

        if (!result) {
            return;
        }

        //cc.log("draw ");

        this.remainLength = this.remainLength - inVec.mag();
        this.refletTimes++;

        if (this.refletTimes > 1) return;

        inVec.normalizeSelf();
        let nor = result.normal;
        let reflectVec = inVec.sub(nor.mul(2 * inVec.dot(nor))).normalize();

        p1 = p2.add(nor.mul(this.ballWidth));

        pos = this.node.convertToNodeSpaceAR(p1);
        this.ctx.moveTo(pos.x, pos.y)
        this.ctx.circle(pos.x, pos.y, BallRaycast.BALL_RADIUS);
        this.ctx.fill();


        p2 = reflectVec.mul(this.reflectLength).add(p1);
        this.rayCast(p1, p2);
    }

}
