var DIR_RECORD = "P2PVideoRecord";
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
    };
}

var context = null;

function _RenderBuildObject(sRenID) {
    return "_RND_" + sRenID;
}

function _RenderObjectIs(sObject) {
    return sObject.indexOf("_RND_") == 0;
}

function _RenderObjectParseRenID(sObject) {
    return sObject.indexOf("_RND_") == 0 ? sObject.substring(5) : "";
}

function _RenderObjectParseShortRenID(sObject) {
    var sPeer = sObject.indexOf("_RND_") == 0 ? sObject.substring(5) : "";

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

function getNowDataString() {
    var currentTime = new Date();

    var sDate = currentTime.format();
    return sDate;
}

function getExternalStoragePublicDirectory(subDir) {
    //Environment.getExternalStorageDirectory() = /mnt/sdcard
    return "D://";
}

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

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 ObjPeerParserID(sObjPeer) {

    if (sObjPeer.indexOf("_CAP_") == 0) {
        return sObjPeer.substring(5);
    } else if (sObjPeer.indexOf("_RND_") == 0) {
        var iInd = sObjPeer.lastIndexOf("_");

        return iInd > 5 ? sObjPeer.substring(5, iInd) : sObjPeer.substring(5);
    }
    return sObjPeer;
}

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

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


/**
 * 一个采集端的例子
 */
function Capture(live, extvideo,m_callFlow, contactManage) {
    this.mLive = live;
    this.extVideo = extvideo;
    this.m_callFlow = m_callFlow;
    this.contactManage = contactManage;

    this.m_bInited = false;
    this.m_bLogin = false;

    this.msSvr = "";
    this.msDevID = "";

    this.prvwSurfaceView = null;
    this.otherSurfaceView = null;

    this.Init = function (Node,sSvr, sID , sPass , sRelayAddr , iTryTime , prvwSurfaceView,otherSurfaceView) {
        if (isEmpty(sSvr) || isEmpty(sID)) {
            return PG_ERR_BadParam;
        }
        this.Node = Node;
        this.msSvr = sSvr;
        this.msDevID = sID;
        var iErr = this.m_callFlow.Initialize(this.msDevID, "", 0, 0);
        if (iErr != pgCallFlowError.OK) {
            Alert("Error", "LiveStart: init call flow failed!");
            return iErr;
        }

        this.mLive.SetNodeEventHook(this.extVideo.getHook());
        iErr = this.mLive.Initialize(this.msDevID, sPass, sSvr,
            sRelayAddr, iTryTime, "(Debug){1}");
        if (iErr != PG_ERR_Normal) {
            console.log("pgLiveCapExter", "LiveStart: Live.Initialize failed!");
            this.m_callFlow.Cleanup();
            return iErr;
        }
        this.prvwSurfaceView = prvwSurfaceView;

        // 初始化 ExtVideo ，获取显示对端的View
        this.extVideo.setOnEvent(this); //设置ExtVideo 的回调。
        var sExtVideoParam = "(Code){3}(Mode){2}(Rate){66}(BitRate){300}";
        iErr = this.extVideo.initialize(Node, this.mLive.GetSelfPeer(), sExtVideoParam, "");
        if (iErr > PG_ERR_Normal) {
            console.log("Capture : extVideo initialize iErr = " + iErr);
            this.mLive.Clean();
            this.m_callFlow.Cleanup();
            return iErr;
        }
        console.log("pgLiveCapExter", "LiveStart: Set callback");
        this.otherSurfaceView = otherSurfaceView;
      
        this.m_bInited = true;
        return PG_ERR_Normal;
    };

    this.Clean = function () {
        
        this.extVideo.clean();
        this.mLive.Clean();
        this.mLive.SetNodeEventHook(null);
        this.extVideo.setOnEvent(null);

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

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

    this.CallCancel = function (sID, sInfo) {
        this.stopPlay(sID);
        return this.m_callFlow.Cancel(sInfo);
    };

    this.CallAccpet = function (sID, sInfo) {

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

    this.CallReject = function (sID, sInfo) {

        return this.m_callFlow.Reject(sInfo);
    };

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

    this.startPlay = function (sID) {
        var iErr = this.startPlayLive(sID);
        if (iErr > 0) {
            showAlert(context, "错误", "启动视频失败。 iErr = " + iErr);
            return iErr;
        }
        
        return iErr;
    };

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

        this.stopPlayLive(sID);
    };

    this.startPlayLive = function (sID) {
        var sVideoParam = "(Code){3}(Mode){3}(Rate){66}" +
            "(Portrait){1}(BitRate){500}(MaxStream){3}(Delay){0}(SendCache){1}";
        var iErr = this.mLive.VideoStart(0, sVideoParam, this.prvwSurfaceView);
        if (iErr > PG_ERR_Normal) {
            return iErr;
        }
        iErr = this.mLive.AudioStart(0, "");
        if (iErr > PG_ERR_Normal) {
            this.mLive.VideoStop(0);
        }
        return iErr;
    };

    this.stopPlayLive = function (sID) {
        this.mLive.VideoStop(0);
        this.mLive.AudioStop(0);
    };

    this.recordStart = function () {
        var sRoot = getExternalStoragePublicDirectory(DIR_RECORD);
        var sFileName = sRoot + "/video_" + getNowDataString() + ".mp4";
        return this.mLive.RecordStart("1314", sFileName, 0, -1);
    };

    this.recordStop = function () {
        this.mLive.RecordStop("1314");
    };

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

    this.reqGetObjPeer = function (sID) {
        if (this.extVideo == null) {
            return PG_ERR_System;
        }
        return this.extVideo.sendGetObjPeer(sID, "");
    };

    this.resGetObjPeer = function (sObjPeer, sParam) {

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

    this.resGetObjPeerNotify = function (sObjPeer, sParam) {
        return this.extStart(sObjPeer);
    };
    //------------------------------------------------------------
    //msObjPeer
    this.msObjPeer = "";
    this.msVideoPeer = "";

    this.extStart = function (sObjPeer) {
        if (sObjPeer.equals(this.msObjPeer)) {
            this.extStop();
        }

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

    this.extStop = function () {
        this.extVideoClose();

        if (!isEmpty(this.msObjPeer)) {
            this.extVideo.stop(this.msObjPeer);
            this.msObjPeer = "";
        }
    };



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

    this.extResVideoStart = function (iErr, sObj, uHandle, sObjPeer) {
        this.msVideoPeer = sObjPeer;
        var iErrRet = this.extVideo.videoHandle(sObj, iErr, uHandle, sObjPeer, this.otherSurfaceView, false);
        if(iErrRet > 0){
            showText("extResVideoStart uHandle = " + uHandle + "; iErr = " + iErrRet);
        }
    };

    this.RenderLeave = function (sPeer) {

    };

    this.RenderJoin = function (sPeer) {


    };


    this.onGetObjPeer = function (sObjPeer, sParam) {
        var iErr = this.resGetObjPeer(sObjPeer, sParam);
        if (iErr > 0) {
            showText(" 回复请求本端节点名称失败 : iErr = " + iErr);
        }
    };

    this.onGetObjPeerReply = function (uErr, sParam) {
        if (uErr > PG_ERR_Normal) {
            showText(" 请求对端节点名称失败 : iErr = " + uErr);
        }
    };

    this.onGetObjPeerNotify = function (sObjPeer, sParam) {
        var iErr = this.resGetObjPeerNotify(sObjPeer, sParam);
        if (iErr > 0) {
            showToast(context, "添加通道失败.");

        }
    };

    this.onVideoSync = function (sObj, sAct, sObjPeer) {
        if ("0".equals(sAct)) {
            //msObjPeer = "";
            //extVideo.stop();
        } else if ("1".equals(sAct)) {
            console.log("onVideoSync");
        }
        return 0;
    };

    this.onVideoStart = function (sObj, uHandle, sObjPeer) {
        showText("收到视频打开请求。uHandle = " + uHandle);
        var iErr =this.extResVideoStart(PG_ERR_Normal, sObj, uHandle, sObjPeer);
        if(iErr  > 0){
            showText("应答视频打开请求失败 iErr = " + iErr);
        }
        return -1;
    };

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

        return 0;
    };

    this.onVideoStop = function (sObj, sObjPeer) {
        //            showText("onVideoStop sObj = " + sObj + " sObjPeer = " + sObjPeer);
        return 0;
    };

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

    this.onAudioSync = function (sObj, sAct) {
        return 0;
    };

    this.onAudioStart = function (sObj, sObjPeer) {
        return 0;
    };

    this.onAudioStartRelay = function (sObj, uErr) {
        return 0;
    };

    this.onAudioStop = function (sObjPeer) {
        return 0;
    };
}
module.exports = Capture;