require('./pgLibError');
var START_CALL_REQUEST = 0;
var START_CALL_RESPONES = 1;

//-----------------------------------------------------------------
// Error codes.

String.prototype.equals = function (obj){
    return this == obj;
};

if (typeof pgCallFlowError == "undefined") {
    var pgCallFlowError = {
        OK: 0,
        NoInit: 1,
        RunTime: 2,
        BadStatus: 3,
        SendFailed: 4,
        BadParam: 5,
        Offline: 6,
        Timeout: 7,
        Network: 8
    };
}

function ExtVideoObjParseID ( sObj){
    var sPeer = sObj.indexOf("EXT_VIDEO_") == 0 ? sObj.substring(10) : "";

    var Ind = sPeer.lastIndexOf("_");
    if(Ind > 0){
        return sPeer.substring(0,Ind);
    }else{
        return sPeer;
    }
}

function ObjPeerParseID(sObj){

    var sPeer =  (sObj.indexOf("_RND_") == 0 || sObj.indexOf("_CAP_") == 0) ? sObj.substring(5) : "";

    var Ind = sPeer.lastIndexOf("_");
    if(Ind > 0){
        return sPeer.substring(0,Ind);
    }else{
        return sPeer;
    }
}

var context = null;
function showToast(context, msg) {
    if(typeof debugOutString == "function" ){
        debugOutString(msg);
    }else{
        console.log(msg);
    }
    
}

function showAlert(context, sTitle, sMsg) {
    alert(sTitle + ": " + sMsg)
}

function isEmpty(s) {
    if (null == s || typeof s != "string")
        return true;
    if (s.length == 0)
        return true;
    return false;
}

function showText(sOut) {
    var sData = "Render: " + sOut;
    if(typeof debugOutString == "function" ){
        debugOutString(sData);
    }else{
        console.log(sData);
    }
}

function Alert(sTitle, sMsg) {
    alert(sTitle + ":" + sMsg);
}


/**
 * @author ctkj
 * @date 2017/8/29
 */

function Render(live, extvideo, callflow,contactManage) {

    var m_Live = this.m_Live = live;
    var extVideo = this.extVideo = extvideo;
    var m_contactManage = this.contactManage = contactManage;
    var m_callFlow = this.m_callFlow = callflow;
    this.m_bInited = false;
    this.m_bLogin = false;

    this.prvwSurfaceView = "";
    this.otherSurfaceView = "";

    this.mExtVideoPrvw = "";
    this.captureSurfaceView = "";


    this.sCapID = "";

    this.GetLive = function () {
        return m_Live;
    };

    this.Init = function (Node,sSvrAddr, sSelfID,sPass, sRelayAddr , iTryTime ,prvwSurfaceView,captureSurfaceView,otherSurfaceView) {

        var iErr = m_callFlow.Initialize(sSelfID, "", 0, 0);
        if (iErr != 0) {
            showAlert("Error", "LiveStart: init call flow failed!");
            return iErr;
        }


        m_Live.SetNodeEventHook(extVideo.getHook());
    
        iErr = m_Live.Initialize(sSelfID,
            sPass, sSvrAddr, sRelayAddr, iTryTime, "(Debug){1}");
        if (iErr != PG_ERR_Normal) {
            console.log("pgLiveRander", "LiveStart: Live.Initialize failed!");
            m_callFlow.Cleanup();
            return iErr;
        }

        //旋转了采集方向(Portrait){1}
        extVideo.setOnEvent(this);
        var sExtVideoParam = "(Code){3}(Mode){2}(Rate){66}(BitRate){300}";
        iErr = extVideo.initialize(Node, m_Live.GetSelfPeer(), sExtVideoParam, "");
        if (iErr != PG_ERR_Normal) {
            console.log("pgLiveRander" + "LiveStart: Live.Initialize failed!");
            m_Live.Clean();
            m_callFlow.Cleanup();
            return iErr;
        }
        this.captureSurfaceView = captureSurfaceView; //pgLibLiveMultiView.Get("v0");
        this.prvwSurfaceView = prvwSurfaceView; //extVideo.getPrewview(320, 240);
        this.otherSurfaceView = otherSurfaceView; //pgLibView.Get("v1");
        extVideo.setPrewview(prvwSurfaceView);

        return iErr;
    };

    this.Clean = function () {
        
        if (extVideo != null) {
            extVideo.clean();
        }

        if (m_Live != null) {
            m_Live.Clean();
        }

        m_callFlow.Cleanup();
        this.m_bLogin = false;
        this.m_bInited = false;
    };

    this.CallRequest = function (sID, sInfo) {
        if (!this.m_bLogin) {
            showToast(null, "还没有登录，请登录后再试");
            return PG_ERR_BadStatus;
        }
        return m_callFlow.Request(sID, sInfo);
    };

    this.CallCancel = function (sID, sInfo) {
        return m_callFlow.Cancel(sInfo);
    };
    this.CallAccpet = function (sID, sInfo) {
        
        contactManage.ContactAdd(sID, sID);
        this.sCapID = sID;
        var iErr = this.startPlay(sID);
        if (iErr > 0) {
            this.sCapID = "";
            return iErr;
        }

        iErr = m_callFlow.Accept(sInfo);
        if (iErr > 0) {
            this.sCapID = "";
            this.stopPlay(sID);
            return iErr;
        }
        iErr = this.reqGetObjPeer(sID,"");
        if(iErr > 0){
            showAlert(context,"错误","启动视频失败。 iErr = " + iErr);
            this.stopPlay(sID);
        }
        return iErr;
    };

    this.CallReject = function (sID, sInfo) {

        return m_callFlow.Reject(sInfo);
    };

    this.CallTerminate = function (sID, sInfo) {
        m_callFlow.Terminate(sInfo);
        this.stopPlay(sID);
    };

    this.startPlay = function (sID) {
        var iErr = this.startPlayLive(sID);
        // this.reqGetObjPeer(sID,"");
        return iErr;
    };

    this.stopPlay = function (sID) {
        this.extStop();
        this.stopPlayLive(sID);
    };

    this.startPlayLive = function (sID) {
        if (m_Live == null) {
            return PG_ERR_System;
        }
        var iErr = m_Live.Connect(sID);
        if (iErr > 0) {
            return iErr;
        }
        iErr = m_Live.VideoStart(sID, 0, "", this.captureSurfaceView);
        if (iErr > 0) {
            m_Live.Disconnect(sID);
            return iErr;
        }

        iErr = m_Live.AudioStart(sID, 0, "");
        if (iErr > 0) {
            m_Live.VideoStop(sID, 0);
            m_Live.Disconnect(sID);
            return iErr;
        }
        return iErr;
    };

    this.stopPlayLive = function (sID) {
        if (m_Live == null) {
            return;
        }

        m_Live.AudioStop(sID, 0);
        m_Live.VideoStop(sID, 0);
        m_Live.Disconnect(sID);
    };

    this.OnError = function (sPeer, iErr) {
        //  EventBus.getDefault().post(new MessageEvent("OnError", "",sPeer,iErr));
    };

    /**
     * 请求播放端视频流程 - 请求节点完整名称
     * @param sPeer 节点ID
     * @param sParam 参数
     * @return 返回错误码
     */
    this.reqGetObjPeer = function (sPeer, sParam) {
        if (extVideo == null) {
            return PG_ERR_BadStatus;
        }
        return extVideo.sendGetObjPeer(sPeer, sParam);
    };

    /**
     * 请求播放端视频流程-同意应答
     * @param sObjPeer 节点完整名称 前缀+ID+（后缀）
     * @param sParam 参数
     * @return 返回错误码
     */
    this.resGetObjPeer = function (sObjPeer, sParam) {
        this.extStart(sObjPeer);

        var iErr = extVideo.sendGetObjPeerNotify(sObjPeer, sParam);
        if (iErr > pgLibError.PG_ERR_Normal) {
            showToast(null, "回复ID对象消息发送失败" + iErr);
            this.extStop();
            return iErr;
        }

        return pgLibError.PG_ERR_Normal;
    };

    /**
     * 获得完整名称后初启动Ext视频模块
     * @param sObjPeer 节点完整名称
     * @param sParam 参数
     * @return 错误码
     */
    this.resGetObjPeerNotify = function (sObjPeer, sParam) {
        this.extStart(sObjPeer);
        if(this.extReqVideoStartStatus == 2){
            this.extReqVideoStart(this.m_Live.GetSelfPeer());
        }
        return pgLibError.PG_ERR_Normal;
    };

    this.msObjPeer = "";
    this.msVideoPeer = "";

    /**
     * 添加视频通道
     * @param sObjPeer 节点完整名称
     * @return 错误码
     */
    this.extStart = function (sObjPeer) {
        this.extStop();

        var iErr = extVideo.start(sObjPeer);
        if (iErr > pgLibError.PG_ERR_Normal) {
            showToast(null, "添加通道失败，错误：" + iErr);
            return iErr;
        }
        this.msObjPeer = sObjPeer;
        return iErr;
    };

    /**
     * 删除通道
     */
    this.extStop = function () {
        this.extVideoStop();
        if (!isEmpty(this.msObjPeer)) {
            extVideo.stop(this.msObjPeer);
            this.msObjPeer = "";
        }
    };

    /**
     * 0 : No request
     * 1 : request ed
     * 2 : request failed
     */
    this.extReqVideoStartStatus = 0;
    this.extReqVideoStart = function (sObjPeer) {
        this.msVideoPeer = sObjPeer;
        var iErr = extVideo.videoStart(sObjPeer, this.otherSurfaceView, true);
        if(iErr > 0 && iErr != PG_ERR_Opened){
            this.extReqVideoStartStatus = 2;
        }
        else{
            this.extReqVideoStartStatus = 1;
        }
    };

    this.extVideoStop = function () {
        if (!isEmpty(this.msVideoPeer)) {
            extVideo.videoStop(this.msVideoPeer, true);
            this.msVideoPeer = "";
        }
    };

    this.onGetObjPeer = function (sObjPeer, sParam) {
        this.resGetObjPeer(sObjPeer, sParam);
    };

    this.onGetObjPeerReply = function (uErr, sParam) {
        if (uErr > 0) {
            var sInfo = "发送请求节点名称失败 : uErr = " + uErr;
            showToast(sInfo);
        }

    };

    this.onGetObjPeerNotify = function (sObjPeer, sParam) {
        var sInfo = "onGetObjPeerNotify : sObjPeer = " + sObjPeer + " sParam = " + sParam;
        
        console.log("ExtVideoEvent " + sInfo);
        this.resGetObjPeerNotify(sObjPeer, sParam);
    };

    this.onVideoSync = function (sObj, sAct, sObjPeer) {
        if ("0".equals(sAct)) {
            //msObjPeer = "";
            //extVideo.stop();
        } else if ("1".equals(sAct)) {
            // var sCaptureID = sObj.substring(10);
            // //
            // if (this.sCapID.equals(sCaptureID)) {
            //     var iErr = this.extReqVideoStart(m_Live.GetSelfPeer());
            //     if (iErr > PG_ERR_Normal) {
            //         showToast(null, "请求视频错误：" + iErr);
            //     }
            //     showToast(null, "正在请求打开视频");
            // }

            var sSelfObjPeer = m_Live.GetSelfPeer();
            var sID1 = ObjPeerParseID(sSelfObjPeer);
            var sID2 = ExtVideoObjParseID(sObj);

            var sID3 = ObjPeerParseID(sObjPeer);
            //
            if(this.sCapID.equals(sID3) && sID1.equals(sID2) ) {
                console.log("ExtVideoEvent onVideoSync : extReqVideoStart");

                var iErr = this.extReqVideoStart(sSelfObjPeer);
                if(iErr > PG_ERR_Normal){
                    showToast(context,"请求视频错误：" + iErr);
                }else{
                    showToast(context,"正在请求打开视频");
                }
               
            }
        }
        //            String sInfo = "onVideoSync : sObj = " + sObj + " sAct = " + sAct + " sObjPeer = " + sObjPeer;
        //            showToast(sInfo);
        return 0;
    };

    this.onVideoStart = function (sObj, uHandle, sPeer) {
        //            String sInfo = "onVideoStart : sObj = " + sObj + " uHandle = " + uHandle + " sPeer = " + sPeer;
        //            showToast(sInfo);
        return -1;
    };

    this.onVideoStartReply = function (sObj, uErr) {
        //            String sInfo = "onVideoStartReply : sObj = " + sObj + " uErr = " + uErr;
        //            showToast(sInfo);
        if (uErr > pgLibError.PG_ERR_Normal) {
            showText("视频打开失败 uErr = " + uErr);
        } else {
            showText("视频打开成功！");
            
            //otherSurfaceView.setZOrderOnTop(true);
        }
        return 0;
    };

    this.onVideoStop = function (sObj, sObjPeer) {
        //            String sInfo = "onVideoStop: " + sObjPeer;
        //            showToast(sInfo);
        return 0;
    };

    this.onVideoFrameStat = function (sObj, sData) {
        showToast("onVideoFrameStat sObj = " + sObj + " sInfo = " + sData);
    };

    this.onAudioSync = function (sObj, sAct) {
        //            String sInfo = "onVideoStop: sObj = " + sObj + " sAct = " + sAct;
        //            showToast(sInfo);
        return 0;
    };

    this.onAudioStart = function (sObj, sPeer) {
        //
        //            String sInfo = "onVideoStop: sObj = " + sObj + " sAct = " + sPeer ;
        //            showToast(sInfo);
        return 0;
    };

    this.onAudioStartRelay = function (sObj, uErr) {
        //
        //            String sInfo = "onVideoStop: sObj = " + sObj + " uErr = " + uErr;
        //            showToast(sInfo);
        return 0;
    };

    this.onAudioStop = function (sPeer) {

        //            String sInfo = "onVideoStop: sPeer = " + sPeer;
        //            showToast(sInfo);
        return 0;
    };


    this.CallFlowMessageReceive = function (sData) {
        var Node = m_Live.GetNode();
        if (Node != null) {
            var sRenID = Node.omlGetContent(sData, "User");
            var sMsg = Node.omlGetContent(sData, "Msg");
            m_callFlow.MessageProc(sRenID, sMsg);
        }
    };

    this.CallFlowMessageReceiveError = function (sData, sRndID) {
        if (sRndID.equals("__callflow")) {
            this.CallFlowMessageError(sData);
        }
    };

    this.CallFlowMessageError = function (sData) {
        var iErrCode = 0;
        try {
            if (!sData.equals("")) {
                iErrCode = parseInt(sData);
            }
        } catch (ex) {
            iErrCode = 0;
        }

        var iMsgErr = 0;
        switch (iErrCode) {
            case PG_ERR_BadObject:
                iMsgErr = pgCallFlowError.Offline;
                break;

            case PG_ERR_BadParam:
                iMsgErr = pgCallFlowError.BadParam;
                break;

            case PG_ERR_Timeout:
                iMsgErr = pgCallFlowError.Timeout;
                break;

            case PG_ERR_Network:
                iMsgErr = pgCallFlowError.ERROR_Network;
                break;
        }

        m_callFlow.MessageError(iMsgErr);
    };

    this.onMessageSend = function (sCallID, sData) {
        var sDataReq = "Forward?(User){" + sCallID + "}(Msg){" + sData + "}";
        var iErr = m_Live.SvrRequest(sDataReq, "__callflow");
        return (iErr < 0 || iErr == PG_ERR_Normal);
    };


}

module.exports = Render;