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

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.flyLeft = -71;
        this.flyRight = 40;
        this.flipRight = 218;

        // 配置方程式的各项数据
        // 飞翔时候的数据
        this.flyX = 195;
        this.flyY = 230;
        this.flyDown = -250;

        // 弹起来时候的数据
        this.flipX = 183;
        this.flipY = 349;
        this.flipDown = -94;
    },

    // update (dt) {},

    // 发球时的方程式
    equation:function(x) {
        // return (x * x - this.flipX * 2 * x + this.flipX * this.flipX) / this.flipDown + this.flipY;
        
        if (x >= this.flyLeft - 10 && x <= this.flyRight) {
            return (x * x - this.flyX * 2 * x + this.flyX * this.flyX) / this.flyDown + this.flyY;
        } else if (x > this.flyRight && x <= this.flipRight) {
            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.flyLeft;
        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.flyLeft - 10 && this.x < this.flyRight) {
            speed = 10;
            state = this.ballconfig.BALL_STATE_MINE_LEFT_TO_RIGHT_FLY;
        } else if (this.x >= this.flyRight && this.x < this.flipRight) {
            speed = 10;
            state = this.ballconfig.BALL_STATE_MINE_LEFT_TO_RIGHT_FLIP;
        } else if (this.x >= this.flipRight) {
            speed = 10;
            state = this.ballconfig.BALL_STATE_DROP_IN_RIVAL;
        }

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

        // 判断是否需要磕碰
        var next = this.x + speed;
        if (this.x < this.flyRight && next > this.flyRight) {
            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();
    },
});
