// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class DragObj extends cc.Component {
    _touchStart: boolean;
    _originPos: any;
    _matched: boolean;
    _matcheNode: cc.Node;
    mainCom: any;
    _sucCall: Function;

    onLoad() {

        this._originPos = this.node.position
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
    }

    onTouchStart() {
        this._touchStart = true;

    }
    onTouchMove(touch: cc.Touch) {
        if (this._touchStart) {
            let delta = touch.getDelta();
            this.node.x += delta.x;
            this.node.y += delta.y;

            if (this.node.getBoundingBoxToWorld().intersects(this._matcheNode.getBoundingBoxToWorld())) {
                cc.log("------contersects-----");
                this._matched = true;

            } else {
                this._matched = false;
            }
        }
    }
    onTouchEnd() {
        this._touchStart = false;
        if (!this._matched) {
            this.mainCom.playLocalAudio("btn");
            cc.tween(this.node).to(0.3, { x: this._originPos.x, y: this._originPos.y }).start();
        } else {
            this.mainCom.playLocalAudio("right");
            this.node.active = false;
            this._matcheNode.getChildByName("lb").active = true;
            cc.tween(this.node.parent).to(0.5, { scale: 0 }, { easing: "sineOut" }).start();
            this._sucCall && this._sucCall();
            // this.node.parent.active = false;
        }
    }
    setMatchNode(node: cc.Node, sucCall: Function) {
        this._matcheNode = node;
        this._sucCall = sucCall;
    }

}
