// 敌方接球，从地方右侧至敌方左侧

var Bump = require("bump")
cc.Class({
    extends: cc.Component,

    properties: {
        g: {
            default: null,
            type: cc.Graphics,
        },

        bump: {
            default: null,
            type: Bump,
        },
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        this.initValues();
    },

    // 初始化
    initValues:function() {
        // 球的状态信息
        this.ballconfig = require("ballconfig");
 
        // 球的运动区间
        this.flyRight = 123;
        this.flyLeft = -21;
        this.flipLeft = -140;

        // 配置方程式的各项数据
        // 飞翔时候的数据
        this.flyX = 0;
        this.flyY = 70;
        this.flyDown = 2.35;

        // 弹起来时候的数据
        this.flipX = -5;
        this.flipY = 25;
        this.flipDown = -80;
    },

    // update (dt) {},

    // 发球时的方程式
    equation:function(x) {
        // return (x * x - this.flipX * 2 * x + this.flipX * this.flipX) / this.flipDown + this.flipY;
        
        if (x <= this.flyRight + 10 && x > this.flyLeft) {
            return x * this.flyDown + this.flyY;
        } else if (x <= this.flyLeft && x > this.flipLeft) {
            return (x * x - this.flipX * 2 * x + this.flipX * this.flipX) / this.flipDown + this.flipY;
        }

        return (x * x - this.flipX * 2 * x + this.flipX * this.flipX) / this.flipDown + this.flipY;
    },

    ballPat:function() {
        this.unschedule(this.patUpdate);
        this.x = this.flyRight;
        this.schedule(this.patUpdate, 1.0 / 60);
    },

    ballStop:function() {
        this.unschedule(this.patUpdate);
    },
    
    patUpdate:function (dt) {
        this.g.clear();

        var speed = 0;
        var state;
        if (this.x <= this.flyRight + 10 && this.x > this.flyLeft) {
            speed = 7;
            state = this.ballconfig.BALL_STATE_RIVAL_RIGHT_TO_LEFT_FLY;
        } else if (this.x <= this.flyLeft && this.x > this.flipLeft) {
            speed = 5;
            state = this.ballconfig.BALL_STATE_RIVAL_RIGHT_TO_LEFT_FLIP;
        } else if (this.x <= this.flipLeft) {
            speed = 5;
            state = this.ballconfig.BALL_STATE_DROP_IN_MINE;
        }

        if (this.stateCallback != null) {
            // 给控制器传递发球左侧的状态
            this.stateCallback(state);
        }

        // 判断是否需要磕碰
        var next = this.x - speed;
        if (this.x > this.flyLeft && next <= this.flyLeft) {
            this.bump.bump(cc.v2(this.x, this.equation(this.x)));
        }

        this.x = next;

        this.g.lineWidth = 3;
        this.g.moveTo(this.x, this.equation(this.x));
        this.g.bezierCurveTo(this.x, this.equation(this.x), this.x - 5, this.equation(this.x - 5), this.x - 10, this.equation(this.x - 10));
        this.g.stroke();
    },
});
