import { exchangeNodePos, 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,
		hintAudioClip: 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
        },
		hintBtn: {
			default: null,
            type: cc.Button
		}

	},

	// 生命周期 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 );
		cc.audioEngine.stop(this.hintAudioID );
	},
	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);

		this.videoplayer.stayOnBottom = true;

	},
	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.hideControlId) {
			clearTimeout(this.hideControlId);
		}
		this.showWolf();
		this.showControler();

		if (!this.finishPlayed) {

			this._armatureDisPlay.playAnimation('begin', 0);
			this.finishAudioID = cc.audioEngine.playMusic(this.finishAudioClip, false, 1);
			cc.audioEngine.setFinishCallback(this.finishAudioID, () => {
				this._armatureDisPlay.playAnimation('normal', 0);
				if (window && window.courseware && window.courseware.nextPage) {
					console.log('call window.courseware.nextPage');
					// window.courseware.nextPage();
				}
				onHomeworkFinish();
				// 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);
			if (window && window.courseware && window.courseware.nextPage) {
					console.log('call window.courseware.nextPage');
					// window.courseware.nextPage();
				}
		}
		// this.videoplayer.currentTime = 0 ;
		// this.ProgressBar.progress = 0;
		// this.barTag.x = 0 ;
		// this.updateBarByTime(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');
		this._armatureDisPlay.playAnimation('normal', 0);
		this.setButtonPlayStatus(true);
		this._isReadyToPlay = true;
		return;

		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();
		this.initListener();

		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.nextPage) {
				window.courseware.nextPage();
			}
			
		}, this);
		this.toggleButton.on(cc.Node.EventType.TOUCH_START, function() {

			this.hideWolf();
			this.delayHideControl();

			cc.audioEngine.stop(this.hintAudioID);
			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);
		this.hintBtn.node.on('click', function() {
			console.log('play hint', (!cc.audioEngine.isMusicPlaying() && !this.videoplayer.isPlaying()));
			if (!cc.audioEngine.isMusicPlaying() && !this.videoplayer.isPlaying()){
				this.hintAudioID = cc.audioEngine.playMusic(this.hintAudioClip, false, 1);
				this._armatureDisPlay.playAnimation('begin', 0);
				cc.audioEngine.setFinishCallback(this.hintAudioID, () => {
					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) => {
			// return;
			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) => {

					this.delayHideControl();

			
			// if (!this.videoplayer.isPlaying() ) {
			// 	return;
			// }
			// console.log("TOUCH_MOVE");
            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;
            
            const dur = this.videoplayer.getDuration();

            this.currentTimeLabel.string = this.formatTime(percent * dur );
			// console.log(percent * dur);
			this.videoplayer.currentTime = 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) => {
		// 	if (this.videoplayer.isPlaying()) {
		// 		const pos = e.getLocation();
		// 		const pPos = this.ProgressBar.node.convertToNodeSpaceAR(pos);
		// 		const 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.add reloadImage();
		// this.addPreloadAudio();
		// this.addPreloadAnima();
		// this.preload();
		// this.prepareAudioClip(this.data.begin_audio_url, 'beginAudioClip');
		this.prepareAudioClip(this.data.finish_audio_url, 'finishAudioClip');
		this.prepareAudioClip(this.data.hint_audio_url, 'hintAudioClip');

		// 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();

		this.controlNode = cc.find("Canvas/Controls");
		this.wolfNode = cc.find("Canvas/catBox");
		
		this.controlNode.active = false;
		this.wolfNode.active = false;
	},

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

		// this.initMask(bgNode);
	},

	initMask(bg) {
		const house = cc.find("Canvas/house")
		const bgMask = cc.find("Canvas/bg_mask");
		bgMask.x = house.x;
		bgMask.y = house.y;

		const pos = exchangeNodePos(bgMask, bg);
		bg.parent = bgMask;
		bg.x = pos.x;
		bg.y = pos.y;
	},

	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;
		if (percent > 1) {
			percent = 1
		}
        this.ProgressBar.progress = percent;
        const dur = this.videoplayer.getDuration();
		console.log('updateBarByPos',percent * dur);
        this.videoplayer.currentTime = percent * dur 
    },
    updateBarByTime(ct){

        this.currentTimeLabel.string = this.formatTime(ct);
        const dur = this.videoplayer.getDuration();
        const percent = ct / dur;
		if (percent > 1) {
			percent = 1
		}
		this.ProgressBar.progress = percent;
        const maxX = this.ProgressBar.node.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
		// console.log('updateBarByTime', newX);
        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);
			const ct = this.videoplayer.currentTime;
            if (ct) {
                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);
            }
        }
	},



	hideControler() {
		this.controlNode.active = false;
		// cc.tween(this.controlNode)
		// .to(0.1, {opacity: 0})
		// .call(() => {
		// 	this.controlNode.active = false;
		// })
		// .start()
	},

	showControler() {
		this.controlNode.active = true;
		// this.controlNode.active = true;
		// this.controlNode.opacity = 0;

		// cc.tween(this.controlNode)
		// .to(0.1, {opacity: 255})
		// .call(() => {

		// })
		// .start()
	},

	hideWolf() {
		this.wolfNode.active = false;
		this.replayBtn.active = false;
		// cc.tween(this.wolfNode)
		// 	.to(0.1, {opacity: 0})
		// 	.call(() => {
		// 		this.wolfNode.active = false;
		// 	})
		// 	.start()
	},

	showWolf() {
		this.wolfNode.active = true;
		this.replayBtn.active = true;

		// this.wolfNode.active = true;
		// this.wolfNode.opacity = 0;

		// cc.tween(this.wolfNode)
		// .to(0.1, {opacity: 255})
		// .call(() => {

		// })
		// .start()
	},

	initListener() {
		// const canvas = cc.find("Canvas");
		this.videoplayer.node.on('touchstart', () => {
			this.showControler();
			this.delayHideControl();
		})

		this.initReplayBtn();
		this.initArrowBtn();
	
	},

	initArrowBtn() {
		const arrow_left = cc.find("Canvas/Controls/arrow_left");
		const arrow_right = cc.find("Canvas/Controls/arrow_right");

		const jumpTime = 3;
		arrow_left.on('touchstart', () => {
			this.videoplayer.currentTime -= jumpTime;
		})

		arrow_right.on('touchstart', () => {
			this.videoplayer.currentTime += jumpTime;
		})
	},


	initReplayBtn() {
		this.replayBtn = cc.find("Canvas/btn_replay");
		this.replayBtn.on('touchstart', () => {
			
			this.hideWolf();
			this.delayHideControl();

			cc.audioEngine.stop(this.hintAudioID);
			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);

		})
	},

	delayHideControl() {
		if (this.wolfNode.active) {
			return;
		}
		if (this.hideControlId) {
			clearTimeout(this.hideControlId);
		}

		this.hideControlId = setTimeout(() => {
			this.hideControler();
		}, 5000);
	},



















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

});
