// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.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.Class({
    extends: cc.Component,

    start () {
        this.init();
        this.initVideoBtn();
        this.addListener();
        this.initdDrag();
    },

    barBaseW: 0, // 进度条宽度
    bgProgress: null, // 进度条背景
    bar: null, // 进度条填充
    dragBtn: null, // 进度条拖拽按钮
    controlBtn: null, // 按钮点击事件挂在这个上面
    playBtn: null, // 播放按钮
    pauseBtn: null, // 暂停按钮
    replayBtn: null, // 重播按钮
    
    properties: {
        setTimeoutIDs: [],
        setIntervalIDs: [],
    },

    init() {
        // console.log("Init video control component.")
        this.bgProgress = cc.find('progress', this.node);
        this.bar = cc.find('progress/bar', this.node);
        this.dragBtn = cc.find('dragButton', this.node);
        this.controlBtn = cc.find('controlButton', this.node);
        this.playBtn = cc.find('controlButton/play', this.node);
        this.pauseBtn = cc.find('controlButton/pause', this.node);
        this.replayBtn = cc.find('controlButton/replay', this.node);

        this.playBtn.active = true;
        this.pauseBtn.active = false;
        this.replayBtn.active = false;
        this.videoStatus = 0; // 0:暂停 1:播放中 2:重播

        this.barBaseW = this.bgProgress.width;;
        this.setProgress(0);
    },

    initVideoBtn() {
        this.controlBtn.addComponent(cc.Button);
        this.controlBtn.on('click', () => {
            if (this.videoStatus==null || this.videoStatus ==0) {
                this.refreshVideoBtnState(1);
                this.node.emit('video_btn_click', true)
            } else if (this.videoStatus ==1) {
                this.refreshVideoBtnState(0);
                this.node.emit('video_btn_click', false)
            }
        });
    },

    userDragStart: null,
    initdDrag() {
        const dragStartX = -520;
		const maxX = this.bgProgress.width + dragStartX ;
		const minX = dragStartX;

		this.dragBtn.off(cc.Node.EventType.TOUCH_START);
		this.dragBtn.on(cc.Node.EventType.TOUCH_START, (e) => {
			this.userDragStart = true;
            this.node.emit('on_drag_button', true);
		});

		this.dragBtn.off(cc.Node.EventType.TOUCH_MOVE);
		this.dragBtn.on(cc.Node.EventType.TOUCH_MOVE, (e) => {
			const worldPos = e.getLocation();
			const localPos = this.dragBtn.parent.convertToNodeSpaceAR(worldPos);

			let newX = localPos.x;
			newX = Math.min(maxX, Math.max(newX, minX));
			this.dragBtn.x = newX;
			const percent =  Math.abs(newX-dragStartX) / Math.abs(this.bgProgress.width);
            this.setProgress(percent);
			this.node.emit('on_drag_percent', percent)
		});

		this.dragBtn.off(cc.Node.EventType.TOUCH_END);
		this.dragBtn.on(cc.Node.EventType.TOUCH_END, (e) => {
            if(this.userDragStart) {
                this.userDragStart = false;
                this.node.emit('on_drag_button', false);
            }
		});

        this.dragBtn.off(cc.Node.EventType.MOUSE_UP);
		this.dragBtn.on(cc.Node.EventType.MOUSE_UP, (e) => {
			if(this.userDragStart) {
                this.userDragStart = false;
                this.node.emit('on_drag_button', false);
            }
		});

        this.dragBtn.off(cc.Node.EventType.TOUCH_CANCEL);
		this.dragBtn.on(cc.Node.EventType.TOUCH_CANCEL, (e) => {
            if(this.userDragStart) {
                this.userDragStart = false;
                this.node.emit('on_drag_button', false);
            }
		});
	},

    // 0:暂停 1:播放中 2:重播
    videoStatus: null,
    refreshVideoBtnState(status) {
        this.videoStatus = status;
        switch(status) {
            case 0: 
                this.playBtn.active = true;
                this.pauseBtn.active = false;
                this.replayBtn.active = false;
            break;
            case 1: 
                this.playBtn.active = false;
                this.pauseBtn.active = true;
                this.replayBtn.active = false;
            break;
            case 2: 
                this.playBtn.active = false;
                this.pauseBtn.active = false;
                this.replayBtn.active = true;
            break;
            default: 
                this.playBtn.active = true;
                this.pauseBtn.active = false;
                this.replayBtn.active = false;
            break;
        };
    },

    addListener() {
        this.node.on('video_play_end', () => {
            // console.log("video_play_end");
            this.refreshVideoBtnState();
        })

        this.node.on('update_video_progress', (value)=>{
            // console.log("update_video_progress");
            if(!this.userDragStart) {
                this.setProgress(value);
            } else {
                // console.log("进度条拖动中")
            }
        })

        this.node.on('update_video_status', (status)=>{
            // console.log("update_video_status", status);
            this.refreshVideoBtnState(status);
        })

        this.node.on('hide_bar', (withAnimation)=>{
            this.hideBar(withAnimation);
        })

        this.node.on('show_bar', (withAnimation)=>{
            this.showBar(withAnimation);
        })

        this.node.on("set_mark_points", (data)=>{
            // console.log("set_mark_points")
            const markPoint = cc.find("markPoint", this.node);
            const markPointsContainer = cc.find("markNode", this.node);
            for(let i=0; i<data.length; i++) {
                const newPoint = cc.instantiate(markPoint);
                newPoint.x = -520 + this.bgProgress.width * data[i];
                newPoint.active = true;
                markPointsContainer.addChild(newPoint);
            }
        })
    },

    // 显示进度条
    showBar(withAnimation) {
        const widget = this.node.getComponent(cc.Widget);
        if(withAnimation) {
            widget.bottom = -100;
            let count = 10;
            let step = 200 / count;
            const _intervalId = setInterval(()=>{
                widget.bottom+=step;
                count--;
                if(count <=0) {
                    widget.bottom = 100;
                    clearInterval(_intervalId)
                }
            },30)
            this.setIntervalIDs.push(_intervalId);
        } else {
            widget.bottom = 100;
        }
    },

    // 隐藏进度条
    hideBar(withAnimation) {
        const widget = this.node.getComponent(cc.Widget);
        if(withAnimation) {
            widget.bottom = 100;
            let count = 10;
            let step = 200 / count;
            const _intervalId = setInterval(()=>{
                widget.bottom-=step;
                count--;
                if(count <=0) {
                    widget.bottom = -100;
                    clearInterval(_intervalId)
                }
            },30)
            this.setIntervalIDs.push(_intervalId);
        } else {
            widget.bottom = -100;
        }
        
    },

    setTimeoutID: null,
    setProgress(progress) {
        const dragStartX = -520;
        this.setTimeoutID = setTimeout(() => {
            const w = this.barBaseW * progress;
            this.bar.width = w;
            if(!this.userDragStart) {
                this.dragBtn.x = dragStartX + w;
            }
        }, 1);
    },

    onDestroy() {
        for(let i=0; i<this.setIntervalIDs.length; i++) {
            clearInterval(this.setIntervalIDs[i]);
        }
        clearTimeout(this.setTimeoutID);
    }
});
