// 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;
// @ts-ignore
if(!cc.Node.EventType.LONG_PRESS) {
    // @ts-ignore
    cc.Node.EventType.LONG_PRESS = 'custom_long_press';
    // @ts-ignore
    cc.Node.EventType.LONG_PRESS_END = 'custom_long_press_end';
}

@ccclass
export default class LongPressButton extends cc.Component {

    touchFlag = false;
    longPressFlag = false;
    touchStartTime = null;
    buttonCallback = null;
    // btnStart = null;
    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.touchFlag = false;
        this.touchStartTime = null;
        //添加按钮触摸监听 长按弹托管弹窗列表
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);

    }

    start () {

    }

    setCallback(cb: any) {
        this.buttonCallback = cb;
    }

    //触摸开始
    touchStart(){
        //触摸开始 
        this.touchFlag = true;
        this.longPressFlag = false;
        //记录下触摸开始时间
        this.touchStartTime = new Date();
    }

    //长按检测函数
    touchHold(){
        if(this.touchFlag && this.touchStartTime != null){
            //判断按钮的按压时长
            let touchHoldTime = new Date();
            let milliseconds = touchHoldTime.getTime() - this.touchStartTime.getTime();
            if(milliseconds > 1000 && !this.longPressFlag){
                this.longPressFlag = true;
                //触发托管事务逻辑 
                // @ts-ignore
                this.node.emit(cc.Node.EventType.LONG_PRESS);
                // this.reset();
            }
        }
    }
    reset() {
        this.touchFlag = false;
        this.touchStartTime = null;
        this.longPressFlag = false;
    }
    //触摸结束
    touchEnd(){
        if (this.longPressFlag) {
            // @ts-ignore
            this.node.emit(cc.Node.EventType.LONG_PRESS_END);
        }
        this.reset();
        //出发单击事务逻辑
        //todo...
    }

    update (dt) {
        //判断是否检测按钮长按状态
        if(this.touchFlag){
            this.touchHold();
        }
    }

    // update (dt) {}
}
