const TrtcEngine = require('trtc-electron-edu-sdk');
const {
    TRTCParams,
    TRTCVideoEncParam,
    TRTCNetworkQosParam,
    TRTCTranscodingConfig,
    TRTCMixUser,
    Rect
  } = require('trtc-electron-edu-sdk/liteav/trtc_define');

  const {
    TRTCVideoStreamType,
    TRTCVideoResolution,
    TRTCVideoFillMode,
    TRTCVideoQosPreference,
    TRTCQosControlMode,
    TRTCAppScene,
    TRTCRoleType,
    TRTCVideoResolutionMode,
    TRTCBeautyStyle,
    TRTCDeviceType,
    TRTCDeviceState,
    TRTCTranscodingConfigMode,
    TRTCVideoPixelFormat,
    TRTCVideoBufferType
  } = require('trtc-electron-edu-sdk/liteav/trtc_define');
  

const log = require('electron-xlog');


module.exports = {
    listeners: {},

    rtcEngine: null,

    /** 初始化接口 */
    init: function () {
        this.log("[TAG-TRTC] init->enter");
        this.rtcEngine = new TrtcEngine();

        this.rtcEngine.on('onError', onError)
        this.rtcEngine.on('onEnterRoom', onEnterRoom)
        this.rtcEngine.on('onUserEnter', onUserEnter)
        this.rtcEngine.on('onUserExit', onUserExit)
        this.rtcEngine.on('onUserVideoAvailable', onUserVideoEvent)
        this.rtcEngine.on('onUserSubStreamAvailable', onUserSubStreamEvent)
        this.rtcEngine.on('onUserAudioAvailable', onUserAudioEvent)
        this.rtcEngine.on('onUserVoiceVolume', onVolume)
        // liteav.setLocalVideoCallback(onLocalVideoData); //暂没提供
        this.rtcEngine.on('onRecvCustomCmdMsg', onRecvCustomCmdMsg)
        this.rtcEngine.on('onDeviceChange', onDeviceChange)
        this.rtcEngine.on('onStatistics', onStatistics)
        this.rtcEngine.on('onFirstVideoFrame', onFirstVideoFrame)

        if (process.platform != 'darwin') {
            this.rtcEngine.setRenderSize(320, 240);
        }else {
            this.rtcEngine.setRenderMode(2);
        }
    },

    //暂缺接口
    getTickCount: function(){
        // return liteav.getTickCount();
        return 0;
    },   

    //房间接口
    enterRoom: function (appid, roomid, mapkey, userid, usersig) {
        let param = new TRTCParams();
        let appScene = TRTCAppScene.TRTCAppSceneLIVE;
        param.sdkAppId = parseInt(appid);
        param.roomId = parseInt(roomid);
        param.userId = userid;
        param.userSig = usersig;
        param.privateMapKey = mapkey;
        param.businessInfo = '';
        param.role = TRTCRoleType.TRTCRoleAudience;
        

        this.log("[TAG-TRTC] enterRoom->param: " + appScene);
        this.rtcEngine.enterRoom(param, appScene)

    },
    exitRoom: function () {
        this.rtcEngine.exitRoom();
    },

    /** 音视频参数 */
    setVideoEncoderParam: function (resolution, fps, bitrate) {

        let encparam = new TRTCVideoEncParam();
        encparam.videoResolution = resolution;
        encparam.resMode = TRTCVideoResolutionMode.TRTCVideoResolutionModeLandscape;
        encparam.videoFps = fps;
        encparam.videoBitrate = bitrate;

        this.rtcEngine.setVideoEncoderParam(encparam);
    },

     //新增接口
    startLocalPreview: function (view) {
        this.rtcEngine.startLocalPreview(view);
        this.rtcEngine.setLocalViewFillMode(TRTCVideoFillMode.TRTCVideoFillMode_Fill);
    },

     //更新接口参数
    startRemoteView: function (id, view) {
        log.info("[TAG-TRTC] startRemoteView->view: "+view+"/"+id);
        this.rtcEngine.startRemoteView(id, view);
        this.rtcEngine.setRemoteViewFillMode(id, TRTCVideoFillMode.TRTCVideoFillMode_Fill);
    },

    //新增接口
    stopRemoteView:function(id){
        return this.rtcEngine.stopRemoteView(id);
    },
    setLocalViewMirror: function(mirror){
        return this.rtcEngine.setLocalViewMirror(mirror);
    },

    //更新接口参数
    startRemoteSubStreamView: function (id, view) {
        this.rtcEngine.startRemoteSubStreamView(id, view);
        this.rtcEngine.setRemoteSubStreamViewFillMode(id, TRTCVideoFillMode.TRTCVideoFillMode_Fill);
    },
    stopRemoteSubStreamView: function(id){
        return this.rtcEngine.stopRemoteSubStreamView(id);
    },

    // setRemoteVideoCallback: function (id, callback) {
    //     return this.rtcEngine.setRemoteVideoCallback(id, callback);
    // },

    enableAudioVolumeEvaluation: function (interval, data) {
        return this.rtcEngine.enableAudioVolumeEvaluation(interval, data);
    },

    //自定义渲染接口回调
    enableCustomRender: function(open, rendercallback) {
        
        if(open) {
            this.rtcEngine.setLocalVideoRenderCallback(
                TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32, 
                TRTCVideoBufferType.TRTCVideoBufferType_Buffer, 
                rendercallback);
        }
        else {
            this.rtcEngine.setLocalVideoRenderCallback(
                TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32, 
                TRTCVideoBufferType.TRTCVideoBufferType_Buffer, 
                null);
        }    
    },

    /** 设置控制 */
    //更新接口参数
    enableCamera: function (enable, view) {
        if (enable) {
            if(view==null){
                this.log("enableCamera view is null " );
            }else{
                log.info("[TAG-TRTC] startLocalPreview->view: "+view);
                this.startLocalPreview(view);
            }
        } else {
            this.rtcEngine.stopLocalPreview();
        }
    },

    // enableCamera: function (enable) {
    //     if (enable) {
    //         if(view==null){
    //             this.log("enableCamera view is null " );
    //         }else{
    //             this.rtcEngine.startLocalPreview(view);
    //         }
    //     } else {
    //         this.rtcEngine.stopLocalPreview();
    //     }
    // },
    enableMic: function (enable) {
        if (enable) {
            this.rtcEngine.startLocalAudio();
        } else {
            this.rtcEngine.stopLocalAudio();
        }
    },
    /** 切换角色 */
    changeAnchorRole: function(enable){
        log.info("[TAG-TRTC] changeAnchorRole->set role: "+(enable ? "Anchor" : "Audience"));
        this.rtcEngine.switchRole(enable ? TRTCRoleType.TRTCRoleAnchor : TRTCRoleType.TRTCRoleAudience)
    },
    getCurrentSpeakerVolume: function () {
        return this.rtcEngine.getCurrentSpeakerVolume();
    },
    setCurrentSpeakerVolume: function (volume) {
        return this.rtcEngine.setCurrentSpeakerVolume(volume);
    },
    getSpeakerDevicesList: function () {
        return this.rtcEngine.getSpeakerDevicesList();
    },
    getMicDevicesList: function () {
        return this.rtcEngine.getMicDevicesList();
    },
    getCameraDevicesList: function () {
        return this.rtcEngine.getCameraDevicesList();
    },
    getCurrentSpeakerDevice: function () {
        return this.rtcEngine.getCurrentSpeakerDevice();
    },
    getCurrentMicDevice: function () {
        return this.rtcEngine.getCurrentMicDevice();
    },
    getCurrentCameraDevice: function () {
        return this.rtcEngine.getCurrentCameraDevice();
    },
    setCurrentSpeakerDevice: function (devId) {
        return this.rtcEngine.setCurrentSpeakerDevice(devId);
    },
    setCurrentMicDevice: function (devId) {
        return this.rtcEngine.setCurrentMicDevice(devId);
    },
    setCurrentCameraDevice: function (devId) {
        return this.rtcEngine.setCurrentCameraDevice(devId);
    },
    startSpeakerDeviceTest: function (file) {
        return this.rtcEngine.startSpeakerDeviceTest(file);
    },
    stopSpeakerDeviceTest: function () {
        return this.rtcEngine.stopSpeakerDeviceTest();
    },
    startMicDeviceTest: function (value) {
        return this.rtcEngine.startMicDeviceTest(value);
    },
    stopMicDeviceTest: function () {
        return this.rtcEngine.stopMicDeviceTest();
    },
    startCameraDeviceTest: function () {
        return this.rtcEngine.startCameraDeviceTest();
    },
    stopCameraDeviceTest: function () {
        return this.rtcEngine.stopCameraDeviceTest();
    },
    setBeautyStyle: function (mode, beauty, white, ruddiness) {
        return this.rtcEngine.setBeautyStyle(mode, beauty, white, ruddiness);
    },




    /** 本地录制 */
    startRecord: function (title, x, y, w, h, slice, path) {
        //   return liteav.startRecord(title, x, y, w, h, slice, path);
    },
    stopRecord: function () {
        //   return liteav.stopRecord();
    },




    /** 屏幕分享 */
    selectScreenCaptureTarget: function (type, id, name, x, y, w, h, mouse, border) {
        return this.rtcEngine.selectScreenCaptureTarget(type, id, name, new Rect(x, y, w, h), mouse, border);
    },
    startScreenCapture: function () {
        return this.rtcEngine.startScreenCapture();
    },
    stopScreenCapture: function () {
        return this.rtcEngine.stopScreenCapture();
    },
    getScreenCaptureSources: function (thumbW, thumbH, w, h) {
        return this.rtcEngine.getScreenCaptureSources(thumbW, thumbH, w, h);
    },






    /** 播片 */
    startVodPlay: function (path, view, loop) {
        return this.rtcEngine.startVodPlay(path, loop, view);
    },
    setVodPlayerStarted: function (callback) {
        this.rtcEngine.on('onVodPlayerStarted', callback);
    },
    setVodPlayerStoped: function (callback) {
        this.rtcEngine.on('onVodPlayerStoped', callback);
    },
    setVodPlayerProgress: function (callback) {
        this.rtcEngine.on('onVodPlayerProgress', callback);
    },
    setVodPlayerError: function (callback) {
        this.rtcEngine.on('onVodPlayerError', callback);
    },
    seekVodPlay: function (pos) {
        return this.rtcEngine.vodSeek(pos);
    },
    pauseVodPlay: function () {
        return this.rtcEngine.pauseVodPlay();
    },
    resumeVodPlay: function () {
        return this.rtcEngine.resumeVodPlay();
    },
    stopVodPlay: function () {
        return this.rtcEngine.stopVodPlay();
    },


    /** 自定义消息 */
    sendCustomCmdMsg: function (cmdId, msg, reliable, order) {
        return this.rtcEngine.sendCustomCmdMsg(cmdId, msg, reliable, order);
    },

    /** 设置回调 */
    setOnError: function (listener) {
        this.listeners.onError = listener;
    },
    setOnEnterRoom: function (listener) {
        this.listeners.onEnterRoom = listener;
    },
    setOnStatistics: function (listener) {
        this.listeners.onStatistics = listener;
    },
    setOnUserEnter: function (listener) {
        this.listeners.onUserEnter = listener;
    },
    setOnUserExit: function (listener) {
        this.listeners.onUserExit = listener;
    },
    setOnUserVideoAvailable: function (listener) {
        this.listeners.onUserVideoEvent = listener;
    },
    setOnUserAudioAvailable: function (listener) {
        this.listeners.onUserAudioEvent = listener;
    },
    setOnUserSubStreamAvailable: function (listener) {
        this.listeners.onUserSubStreamEvent = listener;
    },
    setVolumeCallback: function (listener) {
        this.listeners.onVolume = listener;
    },
    setLocalVideoCallback: function (listener) {
        this.listeners.onLocalVideoData = listener;
    },
    setOnRecvCustomCmdMsg: function (listener) {
        this.listeners.onRecvCustomCmdMsg = listener;
    },
    setOnDeviceChange: function (listener) {
        this.listeners.onDeviceChange = listener;
    },
    setOnFirstVideoFrame: function (listener) {
        this.listeners.onFirstVideoFrame = listener;
    },



    log: function (msg) {
        log.info(msg);
    },
       err: function(msg){
        log.error(msg);
    },




    /**  内部方法 */
    onError: function (code, msg, arg) {
        this.err("[TAG-TRTC] onError->code:" + code + ", msg:" + msg);
        if (this.listeners.hasOwnProperty('onError')) {
            this.listeners.onError(code, msg, arg);
        }
    },
    onEnterRoom: function (elapse) {
        this.log("[TAG-TRTC] onEnterRoom->elapse:" + elapse);
        if (this.listeners.hasOwnProperty('onEnterRoom')) {
            this.listeners.onEnterRoom(elapse);
        }
    },
    onUserEnter: function (id) {
        if (this.listeners.hasOwnProperty('onUserEnter')) {
            this.listeners.onUserEnter(id);
        }
    },
    onUserExit: function (id) {
        if (this.listeners.hasOwnProperty('onUserExit')) {
            this.listeners.onUserExit(id);
        }
    },
    onUserVideoEvent: function (id, enable) {
        if (this.listeners.hasOwnProperty('onUserVideoEvent')) {
            this.listeners.onUserVideoEvent(id, enable);
        }
    },
    onUserAudioEvent: function (id, enable) {
        if (this.listeners.hasOwnProperty('onUserAudioEvent')) {
            this.listeners.onUserAudioEvent(id, enable);
        }
    },
    onUserSubStreamEvent: function (id, enable) {
        if (this.listeners.hasOwnProperty('onUserSubStreamEvent')) {
            this.listeners.onUserSubStreamEvent(id, enable);
        }
    },
    onVolume: function (volumes, totalVolume) {
        if (this.listeners.hasOwnProperty('onVolume')) {
            for (i in volumes){
                this.listeners.onVolume(volumes[i].userId, Math.floor(volumes[i].volume/10));
            }
        }
    },
    onLocalVideoData: function (id, type, width, height, timestamp, rotation, data) {
        if (this.listeners.hasOwnProperty('onLocalVideoData')) {
            this.listeners.onLocalVideoData(id, type, width, height, timestamp, rotation, data);
        }
    },
    onRecvCustomCmdMsg: function (id, cmdId, req, msg) {
        if (this.listeners.hasOwnProperty('onRecvCustomCmdMsg')) {
            this.listeners.onRecvCustomCmdMsg(id, cmdId, req, msg);
        }
    },
    onDeviceChange: function (devId, devType, devState) {
        if (this.listeners.hasOwnProperty('onDeviceChange')) {
            this.listeners.onDeviceChange(devId, devType, devState);
        }
    },
    onStatistics: function (upLoss, downLoss, appCpu, systemCpu, rtt, recvBytes, sentBytes) {
        if (this.listeners.hasOwnProperty('onStatistics')) {
            this.listeners.onStatistics(upLoss, downLoss, appCpu, systemCpu, rtt, recvBytes, sentBytes);
        }
    },
    onFirstVideoFrame(id, streamType, width, height){
        if (this.listeners.hasOwnProperty('onFirstVideoFrame')) {
            this.listeners.onFirstVideoFrame(id, streamType, width, height);
        }
    },
}


/** 外部事件监听(liteav不支持子方法) */
function onError(code, msg, arg) {
    module.exports.onError(code, msg, arg);
}
function onEnterRoom(elapse) {
    module.exports.onEnterRoom(elapse);
}
function onUserEnter(id) {
    module.exports.onUserEnter(id);
}
function onUserExit(id) {
    module.exports.onUserExit(id);
}
function onUserVideoEvent(id, enable) {
    module.exports.onUserVideoEvent(id, enable);
}
function onUserAudioEvent(id, enable) {
    module.exports.onUserAudioEvent(id, enable);
}
function onUserSubStreamEvent(id, enable) {
    module.exports.onUserSubStreamEvent(id, enable);
}
function onVolume(id, volume) {
    module.exports.onVolume(id, volume);
}
function onLocalVideoData(id, type, width, height, timestamp, rotation, data) {
    module.exports.onLocalVideoData(id, type, width, height, timestamp, rotation, data);
}
function onRecvCustomCmdMsg(id, cmdId, req, msg) {
    module.exports.onRecvCustomCmdMsg(id, cmdId, req, msg);
}
function onDeviceChange(devId, devType, devState) {
    module.exports.onDeviceChange(devId, devType, devState);
}
function onStatistics(statis) {
    module.exports.onStatistics(statis.upLoss, statis.downLoss, statis.appCpu, statis.systemCpu, statis.rtt, statis.receivedBytes, statis.sentBytes);
}
function onFirstVideoFrame(id, streamType, width, height){
    module.exports.onFirstVideoFrame(id, streamType, width, height);
}

