import { onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";
function RemoteResourceCounter(count, cb) {
	this.remoteResourceCount = count
	this.currentLoadedResourceCount = 0;
	this.finishCallback = cb;
}
RemoteResourceCounter.prototype.load = function(num) {
	this.currentLoadedResourceCount += num;
	console.log('RemoteResourceCounter', this.remoteResourceCount , this.currentLoadedResourceCount);
	if (this.remoteResourceCount <= this.currentLoadedResourceCount) {
		this.finishCallback && this.finishCallback();
	}
}
const TOGGLE_BUTTON_STATUS = {
	PAUSE: 0,
	PLAY: 1
}
cc.Class({

	extends: cc.Component,

	properties: {
		videoplayer: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.VideoPlayer, // optional, default is typeof default
        },
		cat: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		toggleButton: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		toggleButtonSprite: {
            // ATTRIBUTES:
            default: null,        // The default value will be used only when the component attaching
                                  // to a node for the first time
            type: cc.Node, // optional, default is typeof default
        },
		beginAudioClip: cc.AudioClip,
		finishAudioClip: cc.AudioClip,

		playStatus: {
			default: null, 
			type: cc.SpriteFrame, 
		},
		pauseStatus: {
			default: null, 
			type: cc.SpriteFrame, 
		},
		m1: {
			default: null, 
            type: cc.Sprite,
        },
		m2: {
			default: null, 
            type: cc.Sprite,
        },
		durationLabel: {
            default: null,
            type: cc.Label
        },
        currentTimeLabel: {
            default: null,
            type: cc.Label
        },
        barTag: {
            default: null,
            type: cc.Node
        },
		ProgressBar: {
            default: null,
            type: cc.ProgressBar
        },
		qupeiyinBtn: {
            default: null,
            type: cc.Sprite
        },

	},

	// 生命周期 onLoad
	onLoad() {
		// this.initSceneData();
		this.initSize();
		this._armatureDisPlay = this.cat.getComponent(dragonBones.ArmatureDisplay);
        //获取 Armatrue
        this._armature = this._armatureDisPlay.armature();
		
		
		this._isReadyToPlay = false;
		
		this.toggleButtonSpriteNode = this.toggleButtonSprite.getComponent(cc.Sprite);
		this.setButtonPlayStatus(TOGGLE_BUTTON_STATUS.PAUSE);
		
	},
	onDestroy() {
		this.isPlayMusicAnimation = false;
		cc.audioEngine.stop(this.beginAudioID );
		cc.audioEngine.stop(this.finishAudioID );
	},
	ctor() { 
		this.beginPlayed = false;
		this.finishPlayed = false;
		this.gameStatus = new RemoteResourceCounter(0, this.hideRabbit.bind(this))
		
	},


	onReadyToPlay(player) {
		console.log('onReadyToPlay');
		this.gameStatus.load(1);
		
	},
	onMetaLoaded(player) {
		console.log('onMetaLoaded');
		this.durationLabel.string = this.formatTime(this.videoplayer.getDuration());
	},
	onClicked(player) {
		console.log('onClicked');
	},
	onPlaying(player) {
		console.log('onPlaying');
		// this.videoStatus.isVideoPlaying = true;
		
	},
	// onPaused(player) {
	// 	console.log('onPaused');
	// 	this.videoStatus.isVideoPlaying = false;
	// },
	// onStoped(player) {
	// 	console.log('onStoped');
	// 	this.videoStatus.isVideoPlaying = false;
	// },
	onCompleted(player) {
		console.log('onCompleted');
		// this.videoStatus.isVideoPlaying = false;
		
		if (!this.finishPlayed) {
			this._armatureDisPlay.playAnimation('finish', 0);
			this.finishAudioID = cc.audioEngine.playMusic(this.finishAudioClip, false, 1);
			cc.audioEngine.setFinishCallback(this.finishAudioID, () => {
				this._armatureDisPlay.playAnimation('normal', 0);
				cc.tween(this.qupeiyinBtn.node)
				.to(1, {
					scale: 1
				}, { easing: 'cubicOut' })
				.call(() => {
					// console.log('anim play ends');
				})
				.start();
			});
			this.finishPlayed = true;
		} else {
			this._armatureDisPlay.playAnimation('normal', 0);
		}
		
		this.setButtonPlayStatus(false);
		this.videoplayer.stop();
	},

	prepareAudioClip(url, key) {
		if (url) {
			cc.assetManager.loadRemote(url, (err, audioClip) => {
				if (audioClip) {
					this[key] = audioClip;
				}
				this.gameStatus.load(1);
			});
		} else {
			this.gameStatus.load(1);
		}

		
	},
	hideRabbit() {
		console.log('hideRabbit');
		if (window && window["air"]) {
			window.air.onCourseInScreen = (next) => {
				this.playGame();
				next();
			}
			window["air"].hideAirClassLoading();
		} else {
			this.playGame();
		}
		
	},
	playGame() {
		console.log('playGame');
		if (!this.beginPlayed) {
			this._armatureDisPlay.playAnimation('begin', 0);
			this.beginAudioID = cc.audioEngine.playMusic(this.beginAudioClip, false, 1);
			cc.audioEngine.setFinishCallback(this.beginAudioID, () => {
				this._armatureDisPlay.playAnimation('normal', 0);
				this.setButtonPlayStatus(true);
				this._isReadyToPlay = true;
			});
			this.beginPlayed = true;
		}
	},

	playMusicAnimation(){
		this.isPlayMusicAnimation = true;
		const op1 = this.m1.node.position
		const op2 = this.m2.node.position
		const fn = (sprNode, op) => {
			if (!this.isPlayMusicAnimation) {
				return
			}
			const pos1 = this.getRandomPosInRect(op, 20);
			pos1.angle = this.randRange(-15, 15)
			const pos2 = this.getRandomPosInRect(op, 20);
			pos2.angle = this.randRange(-15, 15)
			const dur1 = this.randRange(0.5, 1.2)
			const dur2 = this.randRange(0.5, 1.2)
			cc.tween(sprNode)
			.to(dur1, pos1, { easing: 'cubicOut' })
			.to(dur2, pos2, { easing: 'cubicIn' })
			.call(() => {
				// console.log('anim play ends');
				fn(sprNode, op);
			})
			.start();
		}
		fn(this.m1.node, op1);
		fn(this.m2.node, op2);
	},
	stopMusicAnimation(){
		this.isPlayMusicAnimation  = false;
	},
	randRange(a, b) {
		const t = [a, b].sort()
		let r = Math.random() * (t[1] - t[0]) 
		if (a >= 1) {
			r =  Math.random() * (t[1] - t[0] + 1) 
		}
		return  r + t[0];
	},
	getRandomPosInRect(target, r) {
		const x = this.randRange(target.x - r, target.x + r);
		const y = this.randRange(target.y - r, target.y + r);
		return {x, y}
	},






	// _imageResList: null,
	// _audioResList: null,
	// _animaResList: null,
	// initSceneData() {
	// 	this._imageResList = [];
	// 	this._audioResList = [];
	// 	this._animaResList = [];
	// },

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {
		// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
		let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
		let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
		let f = screen_size >= design_size
		cc.Canvas.instance.fitHeight = f
		cc.Canvas.instance.fitWidth = !f

		const frameSize = cc.view.getFrameSize();
		this._frameSize = frameSize;

		this._designSize = cc.view.getDesignResolutionSize();

		let sx = cc.winSize.width / frameSize.width;
		let sy = cc.winSize.height / frameSize.height;
		this._cocosScale = Math.min(sx, sy);

		sx = frameSize.width / this._designSize.width;
		sy = frameSize.height / this._designSize.height;
		this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
		this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
	},


	// 生命周期 start
	start() {
		this.initView();

		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}

		getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		});
		this.qupeiyinBtn.node.on(cc.Node.EventType.TOUCH_START, function() {
			console.log(123123);
			if (window.courseware && window.courseware.openDubbingPageTwo) {
				window.courseware.openDubbingPageTwo();
			}
			
		}, this);
		this.toggleButton.on(cc.Node.EventType.TOUCH_START, function() {
			console.log(cc.audioEngine.isMusicPlaying());
			if (cc.audioEngine.isMusicPlaying()) {
				return;
			} 
			cc.audioEngine.stop(this.finishAudioID);
			
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PAUSE) {
				this.setButtonPlayStatus(true);
			} else {
				this.setButtonPlayStatus(false);
			}
			this._armatureDisPlay.playAnimation('normal', 0);
			
			
		}, this);
		cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });
        this.initdDrag();
		window.p = this;
	},
	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) => {
			if (!this.videoplayer.isPlaying()) {
				return
			}
			if (cc.audioEngine.isMusicPlaying()) {
				return;
			}
			if (!this._isReadyToPlay) {
				return;
			}
            console.log("TOUCH_START");
            this.userDragStart = true;
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE,(e) => {
			if (!this.userDragStart ) {
				return;
			}
            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.currentTimeLabel.string = this.formatTime(percent * dur );
        });
        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.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            console.log("MOUSE_UP");
            this.userDragStart = false;
            this.updateBarByPos(this.barTag.x);
        });
        
        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.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");
        });
        // const pgBar = this.ProgressBar.node;
        
    },
	getData(func) {
		if (window && window.courseware) {
			window.courseware.getData(func, 'scene');
			return;
		}

		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.getData(func);
			return;
		}

		func(this.getDefaultData());
	},

	getDefaultData() {
		return defaultData;
	},

	preloadItem() {
		console.log('preloadItem');
		// this.addPreloadImage();
		// this.addPreloadAudio();
		// this.addPreloadAnima();
		// this.preload();
		this.prepareAudioClip(this.data.begin_audio_url, 'beginAudioClip');
		this.prepareAudioClip(this.data.finish_audio_url, 'finishAudioClip');


		// const d = this.data.video_url.lastIndexOf('.');
		// const u = this.data.video_url.substring(0, d) + '_l'  + this.data.video_url.substring(d)
		// console.log('video', u);
		this.videoplayer.remoteURL = this.data.video_url;
		
		cc.debug.setDisplayStats(false);
	},






	initView() {

		this.initBg();
		this.videoplayer.node.on('ready-to-play', this.onReadyToPlay, this);
		this.videoplayer.node.on('meta-loaded', this.onMetaLoaded, this);
		this.videoplayer.node.on('clicked', this.onClicked, this);
		this.videoplayer.node.on('playing', this.onPlaying, this);
		// this.videoplayer.node.on('paused', this.onPaused, this);
		// this.videoplayer.node.on('stopped', this.onStoped, this);
		this.videoplayer.node.on('completed', this.onCompleted, this);

		// this.initPic();
		// this.initBtn();
		// this.initIcon();
	},

	initBg() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;
	},

	setButtonPlayStatus(s) {
		console.log('setButtonPlayStatus', s);
		if (s) {
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PLAY) {
				return;
			}
			this.toggleButtonSpriteNode.spriteFrame= this.pauseStatus;
			this.toggleButton.status = TOGGLE_BUTTON_STATUS.PLAY;
			this.videoplayer.play();
			this.playMusicAnimation();
		} else {
			if (this.toggleButton.status == TOGGLE_BUTTON_STATUS.PAUSE) {
				return;
			}
			this.toggleButtonSpriteNode.spriteFrame= this.playStatus ;
			this.toggleButton.status = TOGGLE_BUTTON_STATUS.PAUSE;
			this.videoplayer.pause();
			this.stopMusicAnimation();
		}
	},
	getButtonPlayStatus() {
		return !!this.toggleButton.status;
	},

    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}`;
    },

	update (dt) {
		if (this.toggleButtonSpriteNode) {
            // console.log(this.userDragStart);
            if (!this.userDragStart) {
                const ct = this.videoplayer.currentTime;
                this.updateBarByTime(ct);
            }

            if (this.videoplayer.isPlaying()) {
				if (this.toggleButton.status === TOGGLE_BUTTON_STATUS.PLAY) {
					return;
				}
                this.setButtonPlayStatus(false);
                
            } else {
				if (this.toggleButton.status === TOGGLE_BUTTON_STATUS.PAUSE) {
					return;
				}
                this.setButtonPlayStatus(true);
            }
        }
	},
























	// ------------------------------------------

});
