// 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
cc.macro.ENABLE_TRANSPARENT_CANVAS = true;
const { ccclass, property } = cc._decorator;

@ccclass
export default class videoCtrl extends cc.Component {

    @property(cc.Node)
    btn_vido: cc.Node = null;

    @property(cc.Node)
    vidoStateIcon: cc.Node = null;

    @property(cc.ProgressBar)
    vidoSlider: cc.ProgressBar = null;
    @property(cc.Node)
    ProgressBar: cc.Node = null;

    @property(cc.Node)
    playbar: cc.Node = null;

    @property(cc.Label)
    nowTime: cc.Label = null;

    @property(cc.Label)
    totalTime: cc.Label = null;
    private _videoCom: cc.VideoPlayer;
    _check: any;
    private _lastTouch: number;

    onLoad() {

        this._lastTouch = -1;
        this.btn_vido.on("click", this.onClickBtn, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.showBtns, this)

        this.node.on(cc.Node.EventType.TOUCH_START, this.touchVideoLayer, this)

        this.initDrag();
    }
    touchVideoLayer() {

        let nowTouch = Date.now();
        if (nowTouch - this._lastTouch < 300) {
            this.onClickBtn();
        }
        this._lastTouch = nowTouch;

    }
    showBtns() {
        this.node.opacity = 255;
        if (this._videoCom.isPlaying()) {
            this.unschedule(this.scheduleHide)
            this.scheduleOnce(this.scheduleHide, 3);
        }

    }
    scheduleHide() {

        this.node.opacity = 0;

    }
    setVideCom(videoCom) {
        this._check = false;
        this._videoCom = videoCom;
        this.unschedule(this.scheduleHide)
        this.scheduleOnce(this.scheduleHide, 3);
    }

    setCanPlay() {
        this.btn_vido.getChildByName("stop").active = false;
        this.btn_vido.getChildByName("play").active = true;
        this.vidoStateIcon.getChildByName("stop").active = false;

    }
    setCanStop() {
        this.btn_vido.getChildByName("stop").active = true
        this.btn_vido.getChildByName("play").active = false;
        this.vidoStateIcon.getChildByName("stop").active = true;
    }
    onClickBtn() {
        this.unschedule(this.scheduleHide)

        let key = this._videoCom.isPlaying()
        this.log("video is playing = " + key)
        if (this._videoCom.isPlaying()) {
            this._videoCom.pause();
            this.setCanPlay();
            this.node.opacity = 255;

        } else {
            this.log("video is resume  ")
            this._videoCom.play();
            this.setCanStop()
            this.scheduleOnce(this.scheduleHide, 3);
        }
    }
    log(str) {
        const node = cc.find('middleLayer');
        if (node) {
            node.getComponent('middleLayer').log(str);
        } else {
            console.log(str);
        }
    }

    update() {
        if (this._videoCom?.currentTime >= 0) {

            if (!this._check) {
                this._check = true;
                // this._videoCom.pause();
                // this.scheduleOnce(() => {
                //     this._videoCom.resume();
                // }, 0)

            }
            let now = Math.ceil(this._videoCom?.currentTime)
            let total = Math.ceil(this._videoCom.getDuration());
            this.nowTime.string = this.makeTimeStr(now)
            this.totalTime.string = this.makeTimeStr(total)
            this.updateSlider(now, total)
        }
    }
    updateSlider(now, total) {
        let percent = now / total
        this.vidoSlider.progress = now / total;
        const maxX = this.ProgressBar.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
        this.barTag.x = newX;
    }
    makeTimeStr(time) {

        let min = Math.floor(time / 60);
        let sec = Math.floor(time % 60);

        return `${min < 10 ? "0" + min : min}:${sec < 10 ? "0" + sec : sec}`

    }

    @property(cc.Node) barTag: cc.Node = null;
    initDrag() {
        const maxX = this.vidoSlider.node.width;
        const minX = 0;

        this.barTag.off(cc.Node.EventType.TOUCH_START);
        this.barTag.on(cc.Node.EventType.TOUCH_START, (e) => {
            console.log("TOUCH_START");
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE, (e) => {
            const worldPos = e.getLocation();
            const localPos = this.barTag.parent.convertToNodeSpaceAR(worldPos);
            let newX = localPos.x;
            newX = Math.min(maxX, Math.max(newX, minX));
            this.barTag.x = newX;
            const percent = newX / maxX;
            const dur = this._videoCom.getDuration();
            
            let now = Math.ceil(this._videoCom?.currentTime)
            let total = Math.ceil(this._videoCom.getDuration());
            this.nowTime.string = this.makeTimeStr(now)
            this._videoCom.currentTime = percent * dur;
        });
        this.barTag.off(cc.Node.EventType.TOUCH_END);
        this.barTag.on(cc.Node.EventType.TOUCH_END, (e) => {
            console.log("TOUCH_ENDED");
            this.updateBarByPos(this.barTag.x);
        });
        this.barTag.off(cc.Node.EventType.MOUSE_UP);
        this.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            console.log("MOUSE_UP");
            this.updateBarByPos(this.barTag.x);
        });
    }

    updateBarByPos(newX) {
        const maxX = this.vidoSlider.node.width;
        const minX = 0;

        let percent = newX / maxX;
        if (percent > 1) {
            percent = 1
        }
        const dur = this._videoCom.getDuration();
        this._videoCom.currentTime = percent * dur
    }
}

