// 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
import GameLogic from "../script/GameLogic"
import { delayCall } from "../script/util";

// cc.game.onStart = function(){
// 	cc.director.runScene(new MyScene());
// 	console.log("Test")
// 	cc.game.run();
// };
// cc.game.run();
cc.Class({

	extends: cc.Component,
	gameLogic: null,
	properties: {

	},

	onStart() {
		
	},

	// 生命周期 onLoad
	onLoad() {
		this.initSceneData();
		this.initSize();
	},

	_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() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}
		

		getData((data) => {
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()

		
		})
	},

	onDestory() {
		cc.audioEngine.stopAll()
		this.gameLogic.destroy()
		
	},

  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() {
		const dataJson = '{"contentObj":{"version":"1.0","key":"DataKey_Sbx_Pronunciation","theme":"D","border_image_url":"","video_image_url":"","text_image_url":"","dataArray":[{"video_url":"http://staging-teach.cdn.ireadabc.com/16eace86b47925cc644797cecd37b03b.mp4","textDragonBones":{"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/e74e4ffcb5c7b3321b448c93969541cd.png","name":"kkKoala_tex.png"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/fca011e0fe39287dc8dd2cd44c0ef7ed.json","name":"kkKoala_tex.json"},"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/d825a8ed1199f157800e11ddb9954146.json","name":"kkKoala_ske.json"}},"rightDragonBones":{"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/aedca82ee5031ab43082c7a08a79b3d6.png","name":"蚂蚁骨骼_animation_tex.png"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/f86dd94a9d56eab7c5f257abc600a577.json","name":"蚂蚁骨骼_animation_tex.json"},"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/5482364adfb24d2b0f627f2767167f4b.json","name":"蚂蚁骨骼_animation_ske.json"}},"rightType":"image","image_url":"http://staging-teach.cdn.ireadabc.com/863035154daca76366204c0d4dddee51.png"}]}}'
		const data = JSON.parse(dataJson);
		return data;
	},

	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},


	addPreloadImage() {

		if (!this.data.dataArray) {
			return;
		}

		this.data.dataArray.forEach(item=>{
			this._imageResList.push({ url: item.question.centerImage_url});
		})
	

	},

	addPreloadAudio() {

		this._audioResList.push({ url: this.data.audio_url });

		const dataArr = this.data.contentObj?.dataArray;
		if (dataArr) {
			dataArr.forEach(data => {

				this._audioResList.push({ url: data.video_url || ''});

			})
		}
		console.log('this.data: ',this.data);
	},

	addPreloadAnima() {
		if (!this.data.dataArray) {
			return;
		}
		this.data.dataArray.forEach((item) => {
			if (item.dragonBones) {
				this._animaResList.push({url: item.dragonBones.skeJsonData.url});
				this._animaResList.push({url: item.dragonBones.texJsonData.url});
				this._animaResList.push({url: item.dragonBones.texPngData.url});
			}
		})
	},

	preload() {

		const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

			this.loadEnd();
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}

			cc.debug.setDisplayStats(false);
		});
	},


	loadEnd() {
		this.initData();
		this.initGameLogic();
		// this.testVideo();
	},

	initGameLogic() {

		// 添加游戏逻辑
		this.gameLogic = new GameLogic(this.data, {
			designSize: this._designSize,
			frameSize: this._frameSize,
			mapScaleMin: this._mapScaleMin,
			mapScaleMax: this._mapScaleMax,
			cocosScale: this._cocosScale,
		});
	},

	testVideo() {



		const videoNode = cc.find("Canvas/temp");
		this.videoNode = videoNode;
		this.videoNode.baseX = videoNode.x;
		videoNode.active = true;
		const vPlayer = videoNode.getComponent(cc.VideoPlayer);
		vPlayer.remoteURL = this.data.contentObj.dataArray[0].video_url;
		this.videoPlayer = vPlayer;
	
		vPlayer.node.on('ready-to-play', () => {

			vPlayer.play();
			checkIsPlaying();
		})

		const checkIsPlaying = () => {

			delayCall(0.001, () => {

				if (vPlayer.currentTime) {
					// vPlayer.pause();
					this.isVideoPlayerReady = true;
					// this.checkCanShowRecordList();

					console.log('aaavbbb');
		
				} else {
					checkIsPlaying();
				}
			})
		}



	
	},

	_cantouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		this._cantouch = true;
	},


















	// ------------------------------------------------
	getSprNode(resName) {
		const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
		const node = new cc.Node();
		node.addComponent(cc.Sprite).spriteFrame = sf;
		return node;
	},

	getSprNode(resName) {
		const sf = cc.find(resName).getComponent(cc.Sprite).spriteFrame;
		const node = new cc.Node();
		node.addComponent(cc.Sprite).spriteFrame = sf;
		return node;
	},


	getSpriteFrimeByUrl(url, cb) {
		cc.assetManager.loadRemote(url, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			if (cb) {
				cb(spriteFrame);
			}
		})
	},

	getSprNodeByUrl(url, cb) {
		const node = new cc.Node();
		const spr = node.addComponent(cc.Sprite);
		this.getSpriteFrimeByUrl(url, (sf) => {
			spr.spriteFrame = sf;
			if (cb) {
				cb(node);
			}
		})
	},

	playAudioByUrl(audio_url, cb = null) {
		if (audio_url) {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				const audioId = cc.audioEngine.play(audioClip, false, 0.8);
				if (cb) {
					cc.audioEngine.setFinishCallback(audioId, () => {
						cb();
					});
				}
			});
		}
	},

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

});
