import { asyncDelay, delayCall, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";


const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
 
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        // this._audioResList.push({ url: this.data.video_url || '' });
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
    }

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

    initView() {


        this.setTransparentCanvas();
        this.initVideo();
        this.initBtn();
        this.initProgress();
        // this.initBg();
        // this.initPic();
        // this.initBtn();
        // this.initIcon();
    }


    playBtn;
    pauseBtn;
    jumpBtn;
    initBtn() {

        const canvas = cc.find("Canvas");

        const jumpBtn = cc.find("Canvas/btn_skip"); //this.getSprNode('btn_right');
        jumpBtn.on('touchstart', () => {
            this.videoPlayEnd();
        })

        if (this.data.isJump != '1') {
            jumpBtn.active = false;
        }
        this.jumpBtn = jumpBtn;


        const playBtn = cc.find('Canvas/btn_play');
        playBtn.on('click', () => {
            console.log(' in click 1')
            this.video.play();
            this.refreshBtnState();
        })
        playBtn.zIndex = 10;
        this.playBtn = playBtn;
        this.playBtn.active = false;


        const pauseBtn = cc.find('Canvas/btn_pause');
        pauseBtn.on('click', () => {
            console.log(' in click 2')
            this.video.pause();
            this.refreshBtnState();
        })
        pauseBtn.zIndex = 10;
        this.pauseBtn = pauseBtn;
        this.pauseBtn.active = false;
    }

    refreshBtnState() {

        // await asyncDelay(0.01);
        if(!this.video) {
            return;
        }
        if (this.video.isPlaying()) {
            this.pauseBtn.active = true;
            this.playBtn.active = false;
        } else {
            this.pauseBtn.active = false;
            this.playBtn.active = true;
        }    
    }


	setTransparentCanvas() {
        // 在main.js 加入以下代码：
        // cc.macro.ENABLE_TRANSPARENT_CANVAS = true;  //加在 cc.game.run(); 前面
        // cc.director.setClearColor(new cc.Color(0,0,0, 0));  //加在cc.game.run(function); 回调里面
        // cc.Camera.main.backgroundColor = new cc.Color(0,0,0, 0);

        // cc.game.canvas.style.backgroundColor =  'rgba(0, 0, 0, 0)'
        // cc.game.canvas.style.backgroundColor = 'transparent';

    }


    video = null
    initVideo() {

        console.log(' in initVideo...')

        if (this.data.video_url) {
            this.getVideoUrl( (url) => {
                this.initVideoRemote(url);
            })
        } 
       

	

    }

    getVideoUrl(callback) {
        const url1 = this.data.video_url;
        const url2 = url1.replace(/.mp4$/g, "_l.mp4");

        this.httpHeadCall(url2, (success) => {

            if (success) {
                console.log('return url2: ', url2);
                callback(url2);
            } else {
                console.log('return url1: ', url1);
                callback(url1);
            }
        })
    }

    isPlayEnd = null
    videoPlayEnd() {
        console.log(' in videoPlayEnd')
        if (this.isPlayEnd) {
            return
        }
        this.isPlayEnd = true;

        if (this.video) {
            this.video.pause();
        }
        onHomeworkFinish();
    }


    initVideoRemote(url) {

        
        console.log(' in initVideoRemote')
        const videoLocalNode = cc.find("Canvas/videoBase/videoLocal");
        videoLocalNode.active = false;

        const videoRemoteNode = new cc.Node();
        videoRemoteNode.width = videoLocalNode.width;
        videoRemoteNode.height = videoLocalNode.height;
        videoRemoteNode.parent = videoLocalNode.parent;
        const video = videoRemoteNode.addComponent(cc.VideoPlayer);

        video.resourceType = cc.VideoPlayer.ResourceType.REMOTE;
        video.remoteURL = url;

        // video.isFullscreen = true;
        video.stayOnBottom = true;

        this.video = video;



        const canvas = cc.find("Canvas");

        video.node.on('meta-loaded', (e) => {
            console.log('meta-loaded e:', e);
        })
        video.node.on('ready-to-play', async (e) => {

            console.log('e: ', e);
			// console.log(' in ready-to-play')
			if (this.isDestroy) {
				return;
			}

            const width = e.node.width;
            const height = e.node.height;

            video.node.width = width;
            video.node.height = height;

            const sx = canvas.width / width;
            const sy = canvas.height / height;
            video.node.scale = Math.min(sx, sy);

            // console.log('canvas: ', canvas);
            // console.log('canvas.width: ', canvas.width);
            // console.log('e.node.width: ', e.node.width);
            // console.log('sx: ', sx);
            // console.log('sy: ', sy);
            // console.log('scale: ', video.node.scale);
			video.play();
            window["air"].hideAirClassLoading();

			checkIsPlaying();
            

		})
        
		const checkIsPlaying = () => {

            console.log('bbbb');

            delayCall( () => {
                
                if (video.currentTime) {
                    console.log(' in aaaa ');
                    // window["air"].hideAirClassLoading();
                    this.refreshBtnState();
                    
                } else {
                    checkIsPlaying();
                }
            }, 0.05)

		}

        this.video.node.on('completed', () => {
            console.log(' in completed!!!!')
            this.videoPlayEnd();
        })

    }


    httpHeadCall(requsetUrl: string, callback) {

        let xhr = new XMLHttpRequest();
        console.log("Status: Send Post Request to " + requsetUrl);
        try {
            xhr.onreadystatechange = () => {
                try{

                    console.log('xhr.readyState: ', xhr.readyState);

                    if (xhr.readyState == 4) {
                        if ((xhr.status >= 200 && xhr.status < 400)) {
                            callback(true);
                        } else {
                            callback(false);
                        }
                    } 

                }catch(e){
                    console.log(e)
                }
            };
    
            xhr.open("HEAD", requsetUrl, true);
            // xhr.setRequestHeader('content-type', 'application/json');
			// xhr.setRequestHeader('token', this.token);

            // xhr.send(JSON.stringify(requestData));       
            xhr.send();


            xhr.timeout = 15000;
			xhr.onerror = (e) => {
				console.log("汪汪汪 posterror", e);
                callback(false);
			};

			xhr.ontimeout = (e) => {
				console.log("汪汪汪 ontimeout", e);
                callback(false);
			};

        } catch (e) {
            console.log("Send Get Request error: ", e)
        }
    }








    // update (dt) {},

    progressJs = null
    initProgress() {

		const progress = cc.find("Canvas/progress")
		const progressJs = progress.getComponent('progressScript');
        this.progressJs = progressJs;

		// const timeLabel = this.getLabel();
		// timeLabel.fontSize = 20;
		// timeLabel.string = Number(formatTime('s.S', new Date(item.duration * 1000))) + 's';
		// item.progressLabel = timeLabel;

		// const timeLabelNode = timeLabel.node;
		// timeLabelNode.anchorX = 0;
		// timeLabelNode.color = cc.Color.BLACK;
		// timeLabelNode.x = progress.x + progress.width + 10;
		// timeLabelNode.y = progress.y;
		// item.addChild(timeLabelNode);
	}


	getPrefab(resName) {
		const prefab = cc.find('Canvas/res/prefab/' + resName)
		const newPrefab = cc.instantiate(prefab);
		newPrefab.parent = null;
		return newPrefab;
	}


    initListener() {

    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }

    update() {

        if (this.progressJs && this.video && !this.isPlayEnd) {
            let percent = this.video.currentTime / this.video.getDuration();
            percent = percent < 0 ? 0 : percent;
            percent = percent > 1 ? 1 : percent;

            // console.log('this.video.currentTime: ', this.video.currentTime);
            // console.log('this.video.getDuration(): ', this.video.getDuration());
            // console.log('percent: ', percent);
            this.progressJs.setProgress(percent);
        }
    }


    isDestroy;
    onDestroy() {
        this.isDestroy = true;
    }
}
