/**
 * 游戏逻辑
 * @author yxx0
 * 绑定场景 Canvas
 */

// require('./liquidfun');

const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property(cc.Node)
    nodeBox: cc.Node = null;

    @property(cc.Node)
    nodeOut: cc.Node = null;

    @property(cc.Graphics)
    graphics: cc.Graphics = null;

    private world: any = null;
    private canUpDate: boolean = false;

    onLoad(): void {
        this.createB2();
    }

    onDestroy(): void {

    }

    /**
     * 初始化
     */
    init(): void {
    }

    /**
     * 销毁
     */
    clear(): void {

    }

    /**
     * 初始化水源
     */
    private createB2(): void {
        let gravity = new b2Vec2(0, -10);    //重力值
        window.world = new b2World(gravity, true);

        var shape = new b2PolygonShape;
        shape.SetAsBoxXYCenterAngle(50 / 2 / 15, 50 / 2 / 15, this.convertToPWorld(this.nodeBox.position), 0);

        var psd = new b2ParticleSystemDef();
        psd.radius = 0.05;
        var particleSystem = window.world.CreateParticleSystem(psd);

        var pd = new b2ParticleGroupDef();
        pd.shape = shape;
        var group = particleSystem.CreateParticleGroup(pd);

        this.scheduleOnce(() => { this.canUpDate = true }, 1)
    }

    update(dt) {
        if (!this.canUpDate) return;
        window.world.Step(dt, 8, 3);
        for (var i = 0, max = window.world.particleSystems.length; i < max; i++) {
            this.drawParticleSystem(window.world.particleSystems[i]);
        }
    }

    private drawParticleSystem(system): void {
        var particles = system.GetPositionBuffer();
        var maxParticles = particles.length;
        var count = 0;
        var minX = this.nodeOut.x - this.nodeOut.width / 2;
        var maxX = this.nodeOut.x + this.nodeOut.width / 2;
        var minY = this.nodeOut.y - this.nodeOut.height / 2;
        var maxY = minY + this.nodeOut.height * 0.6;
        this.graphics.clear();
        for (var i = 0; i < maxParticles; i += 2) {
            let x = particles[i] * 32;
            let y = particles[i + 1] * 32;
            this.graphics.circle(x, y, 0.055 * 32);
            this.graphics.fill();
            if ((minX < x && x < maxX) && (minY < y && y < maxY)) {
                ++count;
            }
        }

        // if (!this.schedulefalg) {
        //     this.scheduleOnce(this.failed, 10);
        //     this.schedulefalg = true;
        // }
        // if (!this.passfalg && count > LIQUID_COUNT) {
        //     this.unschedule(this.failed);
        //     this.scheduleOnce(this.pass, 2);
        //     this.passfalg = true;
        // }
    }

    private convertToPWorld(pos): any {
        return new b2Vec2(pos.x / 32, pos.y / 32);
    }


}
