// var MGOBE = require("./ThirdParty/MGOBE/MGOBE");

// 使用 MGOBE 接口前导入 SDK
// import "./MGOBE/MGOBE.js";

// const Listener = MGOBE.Listener;
// const Room = MGOBE.Room;
let mogobe = {
    // MGOBE 游戏信息
    gameId: "obg-ojj4ptiw",
    secretKey: "bf030e95ebde217416f13efc5a0c73532544f783",
    url: "ojj4ptiw.wxlagame.com",
    cacertNativeUrl: '',
    // 默认匹配 Code
    matchCode: "match-i2iytgmb",
    openId: 'openid_test' + Math.random(), //自定义的用户唯一ID
    roomId:'',
    /**
     * 判断 MGOBE SDK 是否初始化完成
     */
    isInited() {
        // 初始化成功后才有玩家ID
        return !!MGOBE.Player && !!MGOBE.Player.id;
    },
    /**
     * 初始化 MGOBE SDK
     * @param gameInfo
     * @param config
     * @param callback
     */
    // initSDK(gameId, secretKey, url, cacertNativeUrl, callback) {
    initSDK(callback,listener) {
        // 如果已经初始化，直接回调成功
        if (this.isInited()) {
            return callback && callback({code: MGOBE.ErrCode.EC_OK});
        }

        const defaultGameInfo = {
            gameId: this.gameId,
            openId: this.openId,
            secretKey: this.secretKey,
        };

        const defaultConfig = {
            url: this.url,
            isAutoRequestFrame: true,
            cacertNativeUrl: this.cacertNativeUrl,
        };

        // MGOBE.DebuggerLog.enable = true;

        // if (cc.sys.isNative) {
        //     MGOBE.DebuggerLog.enable = false;
        // }
        //是否开启调试
        MGOBE.DebuggerLog.enable = false;
        // 初始化
        let _self = this;
        MGOBE.Listener.init(defaultGameInfo, defaultConfig, event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                console.log("初始化 SDK 成功");
                _self.room = new MGOBE.Room();

                MGOBE.Listener.add(_self.room);
                // 设置默认广播
                _self.room.onJoinRoom = _self.onJoinRoom.bind(_self);
                _self.room.onLeaveRoom = _self.onLeaveRoom.bind(_self);
                _self.room.onRecvFromClient = _self.onRecvFromClient.bind(_self);
                _self.room.onRecvFrame = _self.onRecvFrame.bind(_self);
                _self.room.onStartFrameSync = _self.onStartFrameSync.bind(_self);
                _self.room.onStopFrameSync = _self.onStopFrameSync.bind(_self);
                _self.room.onRecvFromGameSvr = _self.onRecvFromGameSvr.bind(_self);
            } else {
                console.log(`初始化 SDK 失败，错误码：${event.code}`);
            }
            callback && callback(event.code);
        });
    },
    // SDK 发送房间消息
    sendMessage(msg) {
        console.log(`正在发送房间消息`);

        const sendToClientPara = {
            recvPlayerList: [],
            recvType: MGOBE.types.RecvType.ROOM_OTHERS,
            msg,
        };

        this.room.sendToClient(sendToClientPara, event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                console.log(`发送房间消息成功`);
            } else {
                console.log(`发送房间消息失败，错误码：${event.code}`);
            }
        });
    },
    // SDK 发送实时服务器消息
    sendToGameSvr(cmd) {
        console.log(`正在发送房间消息`);

        const sendToGameSvrPara = {
            data: {
                cmd,
            },
        };

        this.room.sendToGameSvr(sendToGameSvrPara, event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                console.log(`发送实时服务器消息成功`);
            } else {
                console.log(`发送实时服务器消息失败，错误码：${event.code}`);
            }
        });
    },
    // SDK 发送帧消息
    sendFrame(cmd) {
        console.log(`正在发送帧消息`);

        const sendFramePara = {
            data: {
                cmd,
            },
        };

        this.room.sendFrame(sendFramePara, event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                console.log(`发送帧消息成功`);
            } else {
                console.log(`发送帧消息失败，错误码：${event.code}`);
            }
        });
    },
    // SDK 开始帧同步
    startFrameSync(callback) {
        console.log(`正在开始帧同步`);

        this.room.startFrameSync({}, event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                console.log(`开始帧同步成功`);
                callback && callback();
            } else {
                console.log(`开始帧同步失败，错误码：${event.code}`);
            }
        });
    },
    // SDK 停止帧同步
    stopFrameSync(success) {

        console.log(`正在停止帧同步`);

        this.room.stopFrameSync({}, event => {
            if (event.code === MGOBE.ErrCode.EC_OK) {
                console.log(`停止帧同步成功`);
                success && success();
            } else {
                console.log(`停止帧同步失败，错误码：${event.code}`);
            }
        });
    },
    onJoinRoom: function (event) {
        console.log("新玩家加入" + event.data.joinPlayerId);
    },
    onLeaveRoom: function (event) {
        console.log("玩家退出" + event.data.leavePlayerId);
    },
    onRecvFromClient: function (event) {
        // console.log("新消息" + event.data.msg);
    },
    onRecvFrame: function (event) {
        this.sendFrame();
        console.log("帧广播", event.data.frame);
        if (event.data.frame.items && event.data.frame.items.length > 0) {
            //console.log("帧广播" + JSON.stringify(event.data.frame.items));
            console.log("帧广播", event.data.frame);
        }
    },
    onStartFrameSync: function (event) {
        this.synced = true;
        console.log("开始帧同步\n");
    },
    onStopFrameSync: function (event) {
        this.synced = false;
        console.log("停止帧同步\n");
    },
    onRecvFromGameSvr: function (event) {
        console.log("新自定义服务消息", event);
        //console.log("新自定义服务消息" + JSON.stringify(event));
    },
    // SDK 随机匹配
    matchPlayers(callback) {
        let matchCode = this.matchCode;

        if (!matchCode) {
            return console.log(`请输入正确的匹配 Code`);
        }

        this.lockSubmit = true;
        this.timerStartMatching = setInterval(() => console.log(`正在随机匹配，请稍等。`), 1000);
        console.log(`正在随机匹配，匹配Code：${matchCode}。请稍等，默认超时时间为 10 秒。`);

        // 注意：这里没有使用匹配属性，如果匹配规则中有设置匹配属性，这里需要做调整
        const matchAttributes = [];

        const playerInfo = {
            name: "测试玩家",
            customPlayerStatus: 0,
            customProfile: "",
            matchAttributes,
        };

        const matchPlayersPara = {
            matchCode,
            playerInfo,
        };

        this.room.initRoom();
        this.room.matchPlayers(matchPlayersPara, event =>
        {
            this.lockSubmit = false;
            clearInterval(this.timerStartMatching);

            if (event.code === MGOBE.ErrCode.EC_OK)
            {
                console.log(`随机匹配成功，房间ID：${event.data.roomInfo.id}`);
                this.roomId = event.data.roomInfo.id;
                callback && callback();
            } else {
                console.log(`随机匹配失败，错误码：${event.code}`);
            }
        });
    },
    //取消随机匹配
    cancelPlayerMatch(callback)
    {
        this.timerEndMatching = setInterval(() => console.log(`正在取消匹配，请稍等。`), 1000);

        const cancelMatchPara = {
            matchType: MGOBE.ENUM.MatchType.PLAYER_COMPLEX,
        };

        this.room.cancelPlayerMatch(cancelMatchPara,event =>
        {
            clearInterval(this.timerStartMatching);
            clearInterval(this.timerEndMatching);

            if (event.code === MGOBE.ErrCode.EC_OK)
            {
                console.log('取消匹配成功');
                callback && callback();
            } else {
                console.log(`取消匹配失败,错误码：${event.code}`);
            }
        });
    }
};
module.exports = mogobe;