// 我方削球，从右侧到右侧

// 角色的方向
var Peel_State = cc.Enum ({
    Peel_Fly: 1,
    Peel_Flip: 2
});

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.state = Peel_State.Peel_Fly;

        // 球的运动区间
        this.flyRight = 159;
        this.flyLeft = 78;
        this.flipRight = 109;

        // 配置方程式的各项数据
        // 飞翔时候的数据
        this.flyX = 75;
        this.flyY = 105;
        this.flyDown = -25;

        // 弹起来时候的数据
        this.flipX = 0;
        this.flipY = -800;
        this.flipDown = 11.8;
    },

    // 发球时的方程式
    equation:function(x) {
        if (this.state == Peel_State.Peel_Fly) {  
            return (x * x - this.flyX * 2 * x + this.flyX * this.flyX) / this.flyDown + this.flyY;
        } else {
            return x * this.flipDown + this.flipY;
        }

        return 0;
    },

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

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

        var speed = 0;
        var state;

        if (this.state == Peel_State.Peel_Fly) {
            if (this.x >= this.flyLeft) {
                speed = -2;
                state = this.ballconfig.BALL_STATE_MINE_RIGHT_TO_RIGHT_FLY;
            } else {
                this.state = Peel_State.Peel_Flip;
            }
        } else {
            if (this.x <= this.flipRight) {
                speed = 1;
                state = this.ballconfig.BALL_STATE_MINE_RIGHT_TO_RIGHT_FLIP;
            } else {
                speed = 1;
                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));
        if (this.state == Peel_State.Peel_Fly) {
            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));
        } else {
            this.g.bezierCurveTo(this.x, this.equation(this.x), this.x + 1, this.equation(this.x + 1), this.x + 2, this.equation(this.x + 2));
        }

        this.g.stroke();
    },

    // update (dt) {},
});
