// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {

        button: {
            default: [],
            type: [cc.Node],
            serializable: true,
        },
        stencil: cc.Node,
        stencil_tip: cc.Node,
        targetButton: {
            default: null,
            type: cc.Node,
            visible:false,
            serializable: false,
        },
    },

    random(max, min) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    },

    onLoad() {
        // this.node.on(cc.Node.EventType.TOUCH_START, this.TouchStartFunction, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.TouchEndFunction, this);
        // this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.TouchCancelFunction, this);
    },

    start() {
        this.stencil_tip.opacity = 255;
        this.stencil_tip.stopAllActions();
        var s = cc.sequence(cc.scaleTo(0.5, 1.5), cc.scaleTo(0.5, 1.0));
        var repeat = cc.repeatForever(s);
        this.stencil_tip.runAction(repeat);
    },

    TouchEndFunction(event) {

        let pt = this.stencil.convertToNodeSpace(event.getLocation());
        let rect = cc.rect(0, 0, this.stencil.width, this.stencil.height);

        //点中空洞，返回false,触摸事件继续派发
        if (rect.contains(pt)) {
            console.log('点击区域');

            if (this.targetButton)
                cc.Component.EventHandler.emitEvents(this.targetButton.clickEvents,event);

            let i = this.random(1, 0);
            console.log(i);
            let button  = this.button[i];
            this.targetButton = button.getComponent(cc.Button);
            let pt = this.stencil.parent.convertToNodeSpaceAR(button.parent.convertToWorldSpaceAR(button.position));
            this.stencil.position = pt;
            this.stencil_tip.position = pt;
            return false;
        }
        console.log('点击区域无效');
    },
    // update (dt) {},

    onButtonEvent(target,event) {
        console.log(target,event);
    }
});
