// 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;
    mainCom: any;
    _sucCall: Function;
    _matchekey: String;
    _matcheList: cc.Node[];
    matcheNode: cc.Node;

    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;
            this.checkMatched();
        }
    }
    checkMatched() {
        this.matcheNode = null;
        for (let i = 0; i < this._matcheList.length; ++i) {
            let matcheNode = this._matcheList[i]
            if (!matcheNode["done"] && this.node.getBoundingBoxToWorld().intersects(matcheNode.getBoundingBoxToWorld())) {
                cc.log("------contersects-----");
                this.matcheNode = matcheNode;
            }
        }
    }
    onTouchEnd() {
        this._touchStart = false;
        if (!this.matcheNode) {
            this.mainCom.playLocalAudio("wrong");
            cc.tween(this.node).to(0.3, { x: this._originPos.x, y: this._originPos.y }).start();
        } else {
            this.matcheNode["done"] = true;
            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;
        }
    }
    setMatchData(key: String, sucCall: Function) {
        this._matchekey = key;
        this._sucCall = sucCall;
    }
    setMatchList(list: Array<cc.Node>) {
        this._matcheList = list;
    }

}
