cc.Class({
    extends: cc.Component,

    properties: {
        // videoPlayer: {
        //     default: null,
        //     type: cc.VideoPlayer
        // },
        ProgressBar: {
            default: null,
            type: cc.ProgressBar
        },
        playButton: {
            default: null,
            type: cc.Button
        },
        pauseButton: {
            default: null,
            type: cc.Button
        },
        restartButton: {
            default: null,
            type: cc.Button
        },
        backButton: {
            default: null,
            type: cc.Button
        },
        forwardButton: {
            default: null,
            type: cc.Button
        },
        durationLabel: {
            default: null,
            type: cc.Label
        },
        currentTimeLabel: {
            default: null,
            type: cc.Label
        },
        barTag: {
            default: null,
            type: cc.Node
        }
        // defaults, set visually when attaching this script to the Canvas
        // text: 'Hello, World!'
    },

    // use this for initialization
    onLoad: function () {
        const {width: dw, height: dh} = cc.view.getDesignResolutionSize();
        const {width: fw, height: fh} = cc.view.getFrameSize();
        const minScale = Math.min(fw/dw, fh/dh);
        // cc.Canvas.instance.node.scale = minScale;


        this._isReadyToPlay = false;
        window['vv'] = this;
        
        cc.macro.ENABLE_TRANSPARENT_CANVAS = true; 
        
        this.node.on('ready-to-play', () => {
            console.log('ready-to-play');
        });
        this.node.on('meta-loaded', () => {
            console.log('meta-loaded');
            this._isReadyToPlay = true;
            this.durationLabel.string = this.formatTime(this.videoPlayer.getDuration());
            // this.videoPlayer.resume();
            this.videoPlayer.stop();
        });
        this.node.on('clicked', () => {
            console.log('clicked');
        });
        this.node.on('playing', () => {
            console.log('playing');
            this.playButton.node.active = false;
            this.pauseButton.node.active = true;
        });
        this.node.on('paused', () => {
            console.log('paused');
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        this.node.on('stopped', () => {
            console.log('stopped');
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        this.node.on('completed', () => {
            console.log('completed');
            this.videoPlayer.currentTime = 0;
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });
        this.initdDrag();
        console.log(11111)
        this.videoPlayer = this.node.getComponent(cc.VideoPlayer);
        this.videoPlayer.getImpl = function() {
            return this._impl;
        }
    },
    initdDrag() {
        const maxX = this.ProgressBar.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.userDragStart = true;
            this.triggerInteractive()
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE,(e) => {
            var delta = e.getDelta();
            let newX = this.barTag.x+delta.x;
            
            newX = Math.min(maxX, Math.max(newX, minX));
            this.barTag.x = newX;
            const percent = newX / maxX;
            // console.log(newX, percent);
            const dur = this.videoPlayer.getDuration();
            // this.videoPlayer.currentTime = percent * dur 
            // this.updateBarByPos(this.barTag.x);
            this.currentTimeLabel.string = this.formatTime(percent * dur );
            this.triggerInteractive()
        });
        this.barTag.off(cc.Node.EventType.TOUCH_ENDED);
        this.barTag.on(cc.Node.EventType.TOUCH_ENDED, (e) => {
           console.log("TOUCH_ENDED");
           this.userDragStart = false;
           this.updateBarByPos(this.barTag.x);
           this.triggerInteractive()
        });
        this.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            console.log("MOUSE_UP");
            this.userDragStart = false;
            this.updateBarByPos(this.barTag.x);
            this.triggerInteractive()
        });
        
        this.barTag.off(cc.Node.EventType.TOUCH_CANCEL);
        this.barTag.on(cc.Node.EventType.TOUCH_CANCEL, (e) => {
           console.log("TOUCH_CANCEL");
           this.userDragStart = false;
           this.updateBarByPos(this.barTag.x);
           this.triggerInteractive() 
        });
        this.ProgressBar.node.off(cc.Node.EventType.TOUCH_START);
        this.ProgressBar.node.on(cc.Node.EventType.TOUCH_START, (e) => {
            const pos = e.getLocation();
            const pPos = this.ProgressBar.node.convertToNodeSpaceAR(pos);
            newX = Math.min(maxX, Math.max(pPos.x, minX));
            this.updateBarByPos(newX);
            // console.log("ProgressBar TOUCH_START", newX); 
        });
        this.node.off(cc.Node.EventType.TOUCH_START);
        this.node.on(cc.Node.EventType.TOUCH_START, (e) => {
           console.log("screen TOUCH_START");
            this.triggerInteractive()
        });
        const pgBar = this.ProgressBar.node;
        this.tw = new (function(){
            this._tw = cc.tween(pgBar).delay(3).to(.6, {
                opacity: 0
            }).call(() => { 
                console.log('This is a callback'); 
                this.running = false;
                // this.displayed = false;
                // this.tw.stop();
                // this.tw.removeSelf()
                // this.tw = null;
            }), 
            this.running = false;
            this.displayed = true;
            this.start = () => {
                this.running = true;
                this.displayed = false;
                pgBar.opacity = 255;
                this._tw.start();
            }
            this.stop = () => {
                this.running = false;
                this.displayed = true;
                this._tw.stop();
                pgBar.opacity = 255;
            }
        });
        // this.tw = cc.tween(this.ProgressBar.node).delay(3).to(.6, {
        //     opacity: 0
        // }).call(() => { 
        //     console.log('This is a callback'); 
        //     // this.tw.stop();
        //     // this.tw.removeSelf()
        //     // this.tw = null;
        // })
    },
    start() {

        // let video0 = document.getElementsByClassName('cocosVideo')[0];
        // console.log(video0);
        // video0.style.zIndex = 5;

        // let gCanvas = document.getElementsByClassName('gameCanvas')[0];
        // console.log(gCanvas);
        // gCanvas.style.position = 'relative';
        // gCanvas.style.zIndex = 10;
        // cc.Camera.main.backgroundColor = cc.color(0, 0, 0, 0);
        // this.videoPlayer.keepAspectRatio = false;


        
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			// console.log('has window');
			getData = window.courseware.getData;
		}
		getData((data) => {
			console.log('data:', JSON.stringify(data));
            this.data = data || this.getDefaultData();
            this.videoPlayer.remoteURL = this.data.video_url;
            // this.preload()
            if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}
        });
        if(window.CustomEvent){
            window.dispatchEvent(new CustomEvent('resize'), true)
        }
    },
    triggerInteractive() {
        this.tw.stop();
        this.ProgressBar.node.opacity = 255;
        this.tw.start();
    },
    checkProgressBarStatus() {
        if (this.videoPlayer.isPlaying()) {
            if (this.tw.displayed) {
                this.tw.start();
            }
        } else {
            this.tw.stop();
            this.ProgressBar.node.opacity = 255 
        } 
    },
    updateBarByPos(newX) {
        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        
        const percent = newX / maxX;
        // console.log(newX, percent);
        const dur = this.videoPlayer.getDuration();
        this.videoPlayer.currentTime = percent * dur 
    },
    updateBarByTime(ct){

        this.currentTimeLabel.string = this.formatTime(ct);
        const dur = this.videoPlayer.getDuration();
        const percent = ct / dur;
        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
        this.barTag.x = newX;
    },
    formatTime(time) {
        if (time === undefined) {
            return '';
          }
          let hh = Math.floor(time / 60 / 60);
          if (hh > 0) {
            hh = `${hh.toString().padStart(2, '0')}:`;
          } else {
              hh = '';
          }
            
          const mm = Math.floor(time / 60).toString().padStart(2, '0');
          const ss = Math.round(time % 60).toString().padStart(2, '0');
      
          return `${hh}${mm}:${ss}`;
    },
    
    getData(func) {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            middleLayerComponent.getData(func);
            return;
        }

		func(this.getDefaultData());
	},
    getDefaultData() {
        // return {video_url: "http://staging-teach.cdn.ireadabc.com/5826aa205a4d33bf65552778b2aaf6f8.mp4"}
		return {video_url: "http://staging-teach.cdn.ireadabc.com/d2b6b86798ef09034bf29417a0e747d2.mp4"}
    },
    
    play(){
        this.videoPlayer.play();
        this.triggerInteractive()
    },
    pause(){
        this.videoPlayer.pause();
        this.triggerInteractive()
    },
    forward(){
        this.videoPlayer.currentTime =this.videoPlayer.getImpl().currentTime() + 5;
        this.triggerInteractive()
    },
    backward(){
        this.videoPlayer.currentTime = this.videoPlayer.getImpl().currentTime() - 5;
        this.triggerInteractive()

    },
    replay(){
        this.videoPlayer.currentTime = 0;
        this.triggerInteractive()
    },

    preload() {
        cc.assetManager.loadAny(this.data, {cacheAsset: true}, null, (err, data) => {
			console.log(' preload data, ', data);
			
			// typeof
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}
		});
	},
    // called every frame
    update: function (dt) {
        // if (this._isReadyToPlay) {
            // const ct = this.videoPlayer.currentTime
             
        // }
        // if (this.wardState && this.videoPlayer.isPlaying()) {
        //     this.wardState = false;
        //     this.pause();
        // }
        if (this.videoPlayer) {
            // console.log(this.userDragStart);
            if (!this.userDragStart) {
                const ct = this.videoPlayer.getImpl().currentTime();
                this.updateBarByTime(ct);
            }
            this.checkProgressBarStatus();
            if (this.videoPlayer.isPlaying()) {
                if (this.playButton.node.active) {
                    this.playButton.node.active = false;
                }
                if (!this.pauseButton.node.active) {
                    this.pauseButton.node.active = true;
                } 
                
            } else {
                if (!this.playButton.node.active) {
                    this.playButton.node.active = true;
                }
                if (this.pauseButton.node.active) {
                    this.pauseButton.node.active = false;
                } 
            }
        }
        
    },
});
