import $ from 'jquery';
import url from 'url';
import xdysdk from "libs/xdysdk";
import ClassDataProxy from "proxy/ClassDataProxy";

import Loger from "Loger";
import  ClassApe from "ape/ClassApe";
import  ChatApe from "ape/ChatApe";
import  MediaManagerApe from "ape/MediaManagerApe";
import  DocApe from "ape/DocApe";
import  WhiteBoardApe from "ape/WhiteBoardApe";
import LaserPen from "ape/LaserPen";
import RecordReplayApe from "ape/RecordRePlayApe";
import UserList from 'ape/UserList';
import ScreenShareApe from 'ape/ScreenShareApe';
import mdetect from "mdetect";
import MediaShareApe from 'ape/MediaShareApe';

// import MusicShareApe from 'ape/MusicShareApe';
import MusicShareApeTwo from 'ape/MusicShareApeTwo';
import AnswerApe from "ape/AnswerApe";
import SignApe from "ape/SignApe";
import localConfig from "local/localConfig";
import UIMagnifyApe from "ape/UIMagnifyApe";
import ErrorApe from 'ape/ErrorApe';

let loger = Loger.getLoger('PCLive');

let _classApe;
let _chatApe;
let _mediaManagerApe;
let _docApe;
let _whiteBoardApe;
let _laserPen;
let _recordReplayApe;
let _screenShareApe;
let _mediaShareApe;
let _musicShareApe;

let _answerApe;
let _signApe;

class Main {
    constructor() {

        let locationProtocol= location.protocol;
        if(locationProtocol=="https:"){
            ClassDataProxy.locationProtocol="https://";
        }else {
            ClassDataProxy.locationProtocol="http://";
        }

        //获取国际化语言
        this._localConfig();
        //获取地址栏参数
        this.getURLParams();

        //课堂初始化和启动流程
        this.init();
        this.addEvent();
    }

    //获取地址栏参数
    getURLParams() {
        let urlParams = this._parseUrlParams();
        loger.log("urlParams", urlParams);
        if (urlParams) {
            ClassDataProxy.classId = parseInt(urlParams.classId) || 0;
            //let userName = urlParams.userName || "user_" + (new Date().getTime() % 1000000);
          let userName = urlParams.userName || "";
            ClassDataProxy.userName = decodeURI(userName);
            ClassDataProxy.userId = urlParams.userId || userName;
            /*if(!ClassDataProxy.userId||ClassDataProxy.userId=="0"){
                ClassDataProxy.userId=userName;
            }*/
            ClassDataProxy.userRole = urlParams.userRole || "normal";
            ClassDataProxy.isRecordPlayBack = Boolean(urlParams.playRecord);
            ClassDataProxy.autoLogin = urlParams.m || 0;

          ClassDataProxy.maxMediaChannels=parseInt(urlParams.channels)||0;
          ClassDataProxy.userRole = urlParams.userRole;
          if(ClassDataProxy.userRole!=ClassDataProxy.USER_HOST&&ClassDataProxy.userRole!=ClassDataProxy.USER_INVISIBLE){
            ClassDataProxy.userRole=ClassDataProxy.USER_NOTMAL;
          }
            //IP+PORT
            let portal = urlParams.portalIP || "";
            let port = urlParams.portalPort || "";
            if (port) {
                portal = portal + ":" + port;
            }
            ClassDataProxy.portal = portal || "";
        }
    }

    //将地址转化成一个对象
    _parseUrlParams() {
        let url = encodeURI(location.search);
        let thisParam = {};
        let strs;
        // 判断是否存在请求的参数
        if (url.indexOf("?") != -1) {
            let str = url.substr(1);
            // 截取所有请求的参数,以数组方式保存
            strs = str.split("&");
            for (let i = 0; i < strs.length; i++) {
                // 获取该参数名称,值。其中值以unescape()方法解码,有些参数会加密
                thisParam[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        // 返回改参数列表对象
        return thisParam;
    }

    //初始化界面
    init() {
        loger.log("init");

        //xdysdk.api("setDebugInfo",{isDebug:false});//不开启日志输出
        //'xdysdk.api("setOpenSendLogToServer",{isOpen:false});//不上报日志

        //显示图片大图
        UIMagnifyApe.init($('#magnifyBox'));

        //创建模块
        //课堂模块
        _classApe = new ClassApe();
        _classApe.on(ClassApe.CLASS_STOP_MEDIA_PUBLISH, this._onClassStopMediaPublishHandler.bind(this));

        //答题卡模块
        _answerApe = new AnswerApe();
        //签到模块
        _signApe = new SignApe();

        //聊天模块
        _chatApe = new ChatApe();
        _chatApe.on(UserList.WINDOW_VIEW_CHANGE, this.onWindowViewChange.bind(this));//监听用户列表模块布局发生改变,文档模块的大小需要调整

        //音频模块
        //_audioApe = new AudioApe();
        //文档模块
        _docApe = new DocApe();
        _docApe.on(DocApe.DOC_IMAGE_LOAD, this._docImageLoadHandler.bind(this));
        _docApe.on(DocApe.SCENE_DOC_CHANGE, this._onSceneChangeHandler.bind(this));

        //标注模块
        _whiteBoardApe = new WhiteBoardApe();
        //激光笔模块
        _laserPen = new LaserPen();
        //录制回放模块
        _recordReplayApe = new RecordReplayApe();
        _recordReplayApe.on(RecordReplayApe.RECORD_REPLAY_PLAY, this._onRecordReplayPlayHandler.bind(this));
        _recordReplayApe.on(RecordReplayApe.RECORD_REPLAY_SEEK, this._onRecordReplaySeekHandler.bind(this));
        _recordReplayApe.on(RecordReplayApe.RECORD_REPLAY_PAUSE, this._onRecordReplayPauseHandler.bind(this));
        _recordReplayApe.on(RecordReplayApe.RECORD_REPLAY_STOP, this._onRecordReplayStopHandler.bind(this));

        _screenShareApe = new ScreenShareApe();
        _screenShareApe.on(ScreenShareApe.SCENE_SCREEN_SHARE_CHANGE, this._onSceneChangeHandler.bind(this));

         _mediaShareApe = new MediaShareApe();
         _mediaShareApe.on(MediaShareApe.SCENE_MEDIA_SHARE_CHANGE, this._onSceneChangeHandler.bind(this));

        // _musicShareApe = new MusicShareApe();
        // _musicShareApe.on(MusicShareApe.SCENE_MUSIC_SHARE_CHANGE, this._onSceneChangeHandler.bind(this));
        _musicShareApe = new MusicShareApeTwo();
        _musicShareApe.on(MusicShareApeTwo.SCENE_MUSIC_SHARE_CHANGE, this._onSceneChangeHandler.bind(this));
        //视频模块
        _mediaManagerApe = new MediaManagerApe();
        _mediaManagerApe.on(MediaManagerApe.FLASH_LOADED, this._onFlashLoaded.bind(this));
        //_mediaManagerApe.startLoadFlashTools();
        this._onFlashLoaded();
    }

    //监听文档、媒体共享、屏幕共享模块的切换
    _onSceneChangeHandler(_sceneName) {
        switch (_sceneName) {
            case ClassDataProxy.SCENE_MEDIA_SHARE:
                if (_screenShareApe) {
                    _screenShareApe.stopAndHide();
                }
                //切换到媒体模块的时候文档模块模式需要全部显示
                if (_docApe) {
                    _docApe.stopAndHide();
                }
                if (_musicShareApe) {
                    _musicShareApe.stopAndHide();
                }
                if (!ClassDataProxy.isRecordPlayBack && ClassDataProxy.userRole == ClassDataProxy.USER_HOST) {
                    xdysdk.api('sceneTableChange', {currentSceneTableId: ClassDataProxy.SCENE_MEDIA_SHARE})
                }
                break;
            case ClassDataProxy.SCENE_MUSIC_SHARE:
                //切换到媒体模块的时候文档模块模式需要全部显示
                if (_mediaShareApe) {
                    _mediaShareApe.stopAndHide();
                }
                if (_screenShareApe) {
                    _screenShareApe.stopAndHide();
                }
                if (!ClassDataProxy.isRecordPlayBack && ClassDataProxy.userRole == ClassDataProxy.USER_HOST) {
                    xdysdk.api('sceneTableChange', {currentSceneTableId: ClassDataProxy.SCENE_DOC})
                }
                break;
            case ClassDataProxy.SCENE_SCREEN_SHARE:
                if (_mediaShareApe) {
                    _mediaShareApe.stopAndHide();
                }
                if (_musicShareApe) {
                    _musicShareApe.stopAndHide();
                }
                //切换到媒体模块的时候文档模块模式需要全部显示
                if (_docApe) {
                    _docApe.stopAndHide();
                }
                if (!ClassDataProxy.isRecordPlayBack && ClassDataProxy.userRole == ClassDataProxy.USER_HOST) {
                    xdysdk.api('sceneTableChange', {currentSceneTableId: ClassDataProxy.SCENE_SCREEN_SHARE})
                }
                break;
            case ClassDataProxy.SCENE_DOC:
                if (_mediaShareApe) {
                    _mediaShareApe.stopAndHide();
                }
                if (_screenShareApe) {
                    _screenShareApe.stopAndHide();
                }
                if (!ClassDataProxy.isRecordPlayBack && ClassDataProxy.userRole == ClassDataProxy.USER_HOST) {
                    xdysdk.api('sceneTableChange', {currentSceneTableId: ClassDataProxy.SCENE_DOC})
                }
                break;
            default:
                break;
        }
    }

    onWindowViewChange() {
        //改变文档模块的布局
        if (_docApe) {
            _docApe.onWindowResize()
        }

    }

    //添加sdk事件监听
    addEvent() {
    }

    //先加载flash资源,加载完成后再加入课堂
    _onFlashLoaded() {
        loger.log("资源加载完成");
        this.startClassRun();
    }

    //开启启动加入课堂的流程
    startClassRun() {
        loger.log('开启启动加入课堂的流程');
        if (_classApe) {
            _classApe.startClassRun();
        }
    }

    //课堂class
    //停止所有推流
    _onClassStopMediaPublishHandler(_data) {
        if (_mediaManagerApe) {
            _mediaManagerApe.stopAllPublishMedia();
        }
        if (_screenShareApe) {
            _screenShareApe.stopAndHide();
        }
    }

    //文档
    _docImageLoadHandler(_data) {
        if (_whiteBoardApe) {
            //设置白板的canvas大小
            _whiteBoardApe.setCanvasSize(_data);
        }
        if (_laserPen) {
            _laserPen.setCanvasSize(_data)
        }
    }

    //录制回放------------------------------------
    //录制回放-播放
    _onRecordReplayPlayHandler() {
        //如果音视频暂停了,录制回放继续的时候音视频也要恢复
        if (_mediaManagerApe) {
            _mediaManagerApe.play();
        }
        if (_screenShareApe) {
            _screenShareApe.play();
        }
        if (_mediaShareApe) {
            _mediaShareApe.play();
        }
        if (_musicShareApe) {
          _musicShareApe.play();
        }
    }

    //录制回放-暂停
    _onRecordReplayPauseHandler() {
        //如果音视频正在播放,录制回放暂停的时候音视频也要暂停
        if (_mediaManagerApe) {
            _mediaManagerApe.pause();
        }
        if (_screenShareApe) {
            _screenShareApe.pause();
        }
        if (_mediaShareApe) {
            _mediaShareApe.pause();
        }
        if (_musicShareApe) {
            _musicShareApe.pause();
        }
    }

    //录制回放-SEEK,需要清除各个模块的数据显示
    _onRecordReplaySeekHandler() {
        if (_classApe) {
            _classApe.clear();
        }
        if (_chatApe) {
            _chatApe.clear();
        }
        if (_mediaManagerApe) {
            _mediaManagerApe.clear();
        }
        if (_docApe) {
            _docApe.clear();
        }
        if (_whiteBoardApe) {
            _whiteBoardApe.clear();
        }
        if (_screenShareApe) {
            _screenShareApe.clear();
        }
        if (_mediaShareApe) {
            _mediaShareApe.clear();
        }
        if (_musicShareApe) {
          _musicShareApe.clear();
        }
    }

    //录制回放-停止
    _onRecordReplayStopHandler() {
        if (_mediaManagerApe) {
            _mediaManagerApe.stop();
        }
        if (_docApe) {
            _docApe.stop();
        }
        if (_screenShareApe) {
            _screenShareApe.stop();
        }
        if (_mediaShareApe) {
            _mediaShareApe.stop();
        }
        if (_musicShareApe) {
          _musicShareApe.stop();
       }
    }

    //获取国际化语言
    _localConfig() {
        let language = navigator.language || navigator.browserLanguage;
        language = language.toLocaleLowerCase();
        loger.log("language:", language);
        if (language == "en-us" || language == "en-gb") {
            language = "en-us";
            ErrorApe.language = 'en_us';
        } else {
            language = "zh-cn";
        }
        loger.log("language-use:", language);
        ClassDataProxy.localConfig = localConfig[language];

        if (!ClassDataProxy.localConfig) {
            ClassDataProxy.localConfig = localConfig['zh-cn'];
        }
    }
}
module.exports = new Main();