import Connect from './Connect';
import onfire from '../framework/onfire';
import Common from '../common/Common';
import Event from '../net/Event';
import ConstMsgId from '../net/ConstMsgId';
import LogicUnitManager from '../framework/LogicUnitManager';
import DataModelManager from '../framework/DataModelManager';
import NetConfig from '../net/NetConfig';
import Define from '../common/Define';

cc.game.config.showFPS = false

export default class GameProcessManager 
{
    constructor()
    {
        cc.log("constructor GameProcessManager start ")
        if( GameProcessManager.unique !== undefined ){
            return GameProcessManager.unique; 
        }
        if(CC_WECHATGAME)
        {
            // H5SDK.init({
            //     wxappid: Common.appid,
            //     gameVersion:'1.0.3'
            // });
        }        //初始化监听回调函数

        this._gameConnect = new Connect("",false)
        this._lum = LogicUnitManager;
        this._ddm = DataModelManager;
        this.socketType = Define.SOCKET_TYPE.GAME
        this.playerInfoModel = this._ddm.getModel('PlayerInfoModel');
        //this.loadProto();
        this._socketConnectOkCallback = null

        // if(CC_JSB && cc.sys.OS_ANDROID === cc.sys.os)
        // {
        //     if(NetConfig.AndroidMainAddress.length<=1)
        //     {
                
        //         this.createSocket(NetConfig.AndroidMainAddress[0].address,null,Define.SOCKET_TYPE.PLAZA);        
        //     }
        //     else
        //     {
        //         var idx = Math.floor((Math.random() * NetConfig.AndroidMainAddress.length)) ;
        //         this.createSocket(NetConfig.AndroidMainAddress[idx].address,null,Define.SOCKET_TYPE.PLAZA);        
    
        //     }
        // }
        // else
        // {
        //     if(NetConfig.mainAddress.length<=1)
        //     {
                
        //         this.createSocket(NetConfig.mainAddress[0].address,null,Define.SOCKET_TYPE.PLAZA);        
        //     }
        //     else
        //     {
        //         var idx = Math.floor((Math.random() * NetConfig.mainAddress.length)) ;
        //         this.createSocket(NetConfig.mainAddress[idx].address,null,Define.SOCKET_TYPE.PLAZA);        
    
        //     }
        // }
       
      
        cc.log("constructor GameProcessManager end ")

        GameProcessManager.unique = this
        //this._onProtoLoaded()
    }


    createSocket(url,successCallback,socketType)
    {
        // if(this._gameConnect)
        // {
        //     this._gameConnect.close()
        // }
        this.socketType = socketType
        this._socketConnectOkCallback = successCallback
        this._gameConnect._url = url
        this._gameConnect.open(false);        
        this._gameConnect._socketType = socketType

        this._gameConnect.off(Event.SOCKET_MSG.DATA)
        this._gameConnect.off(Event.SOCKET_MSG.OPEN)
        this._gameConnect.off(Event.SOCKET_MSG.RECONNECT_START)
        this._gameConnect.off(Event.SOCKET_MSG.RECONNECT_OK)

        this._gameConnect.on(Event.SOCKET_MSG.DATA,this.onData.bind(this),this)
        this._gameConnect.on(Event.SOCKET_MSG.OPEN,this.onOpen.bind(this),this)
        this._gameConnect.on(Event.SOCKET_MSG.RECONNECT_START,this.onReConnectStart.bind(this),this)
        this._gameConnect.on(Event.SOCKET_MSG.RECONNECT_OK,this.onConnectOk.bind(this),this)

    }


    closeSocket()
    {
        this._gameConnect.close()
        
    }

    getSocketState()
    {
       return this._gameConnect.getConnectState()
    }

    onData(sender,msg)
    {
        var wMainCmdID = msg[0]
        var wSubCmdID = msg[1]
        var buf = msg[2]

        // console.log('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');
        // Common.Print("GameProcessManager onData  msg wMainCmdID :" + wMainCmdID + "wSubCmdID:" + wSubCmdID);
    
        // if(wMainCmdID === 0 && wSubCmdID === 1)
        // {
        //     this._gameConnect.close()
        // }
    if(this.socketType === Define.SOCKET_TYPE.PLAZA ) // 大厅socket
    {
        if (ConstMsgId.MDM_MB_LOGON === wMainCmdID) {
            if (ConstMsgId.SUB_MB_LOGON_WX === wSubCmdID) {
                var str = Common.ab2str(buf)
                Common.InspectPrint(str)
                this._lum.getBehavior('LoginBehavior').setData(wMainCmdID,wSubCmdID,str)
                this._lum.getBehavior('LoginBehavior').emit(Event.COM_MSG.AUTH_OK,str)
            } else if (ConstMsgId.SUB_MB_LOGON_SUCCESS === wSubCmdID) {
                this._lum.getBehavior('LoginBehavior').setData(wMainCmdID,wSubCmdID,buf)
                this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.LOGON_SUCCESS,buf)
            } else if (ConstMsgId.SUB_MB_LOGON_FAILURE === wSubCmdID) {
                this._lum.getBehavior('LoginBehavior').setData(wMainCmdID,wSubCmdID,buf);
            }
        } else if (ConstMsgId.MDM_GP_LOGON === wMainCmdID) {
            this._lum.getBehavior('LoginBehavior').setData(wMainCmdID,wSubCmdID,buf)
        } else if (ConstMsgId.MDM_MB_SERVER_LIST === wMainCmdID) {
            if (ConstMsgId.SUB_MB_LIST_SERVER === wSubCmdID) {
                this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)
                this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.SERVER_LIST,buf)
            }
        } else if (ConstMsgId.MDM_GP_USER_SERVICE === wMainCmdID) {
            if (ConstMsgId.SUB_GP_GROWLEVEL_PARAMETER === wSubCmdID) {
                this._lum.getBehavior('LoginBehavior').setData(wMainCmdID, wSubCmdID, buf);
            }
        }
    }
    else if(this.socketType === Define.SOCKET_TYPE.GAME) //游戏socket
    {     
         if (ConstMsgId.MDM_GR_LOGON === wMainCmdID)// 
        {
            console.log("ConstMsgId.MDM_GR_LOGON")
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)
        }
        else if (ConstMsgId.MDM_GR_CONFIG === wMainCmdID)// 
        {
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)
        }
        else if (ConstMsgId.MDM_GR_USER === wMainCmdID)// 
        {
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)
        }
        else if(ConstMsgId.MDM_GR_STATUS === wMainCmdID) //桌子状态
        {
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)
        }
        else if(ConstMsgId.MDM_GF_FRAME === wMainCmdID) //游戏状态 
        {
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)

        }
        else if(ConstMsgId.MDM_GF_GAME === wMainCmdID)// 游戏协议
        {
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)

        }
        else if(ConstMsgId.MDM_GR_INSURE === wMainCmdID)
        {
            this._lum.getBehavior('BattleBehavior').setData(wMainCmdID,wSubCmdID,buf)

        }                      

    }
        // else if (msgId == ConstMsgId.SC.StartRoundNotify)// 开始第n轮(第n题)答题
        // {
            
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.ROUND_START,pb);
        // }
        // else if (msgId == ConstMsgId.SC.AnswerResponse)// 收到自己第n轮(第n题)答题反馈
        // {
        //     this._lum.getBehavior('BattleBehavior').setData(msgId, pb);
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.ANSWER_RESPONCE,pb);
        // }
        // else if (msgId == ConstMsgId.SC.RoundAnswerEndNotify)// 收到第n轮答题结束
        // {
        //     this._lum.getBehavior('BattleBehavior').setData(msgId, pb);
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.ROUND_END,pb);
        // }
        // else if (msgId == ConstMsgId.SC.AnswerBattleEndingNotify)// 收到答题对局结束
        // {
        //     this._lum.getBehavior('BattleBehavior').setData(msgId, pb);
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.BATTLE_END,pb);
            
        // }
        // else if (msgId == ConstMsgId.SC.UnMatchResponse)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.UNMATCH,pb);
        // }
        // else if (msgId == ConstMsgId.SC.BattleAgainResponse)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.BATTLE_AGAIN, pb);
        // }
        // else if (msgId == ConstMsgId.SC.LeaveBattleResponse)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.LEAVE_BATTLE, pb);
        // }
        // else if (msgId == ConstMsgId.SC.PlayerLeaveNotify)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.PLAVER_LEAVE, pb);
        // }
        // else if (msgId == ConstMsgId.SC.PlayerBattleAgainNotify)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.BATTLE_AGAIN_READY, pb);
        // }
        // else if (msgId == ConstMsgId.SC.RoleBaseInfoNotify)
        // {
        //     this._lum.getBehavior('LoginBehavior').setData(msgId,pb);
        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.ROLE_BASEINFO_NOTIFY,pb);

        // }        
        // else if (msgId == ConstMsgId.SC.CreateFriendPkRoomResponse)
        // {
        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.CREATE_FRIEND_PK_ROOM, pb);

        // }
        // else if (msgId == ConstMsgId.SC.EnterFriendPkRoomResponse)
        // {
        //     console.log('Event.CPT_MSG.ENTER_FRIEND_PK_ROOM');
        //     this._lum.getBehavior('LoginBehavior').setData(msgId,pb);

        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.ENTER_FRIEND_PK_ROOM, pb);
        // }
        // // else if (msgId == ConstMsgId.SC.PullStrengthInfoResponse)
        // // {
        // //     this._lum.getBehavior('LoginBehavior').setData(msgId,pb);
        // //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.REFRESH_STRENGTH, pb);
        // // }
        // else if(msgId == ConstMsgId.SC.InformResponse)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.INFORM_RESPONSE, pb);

        // }        
        // else if(msgId == ConstMsgId.SC.PlayerLoadingRateNotify)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.LOADING_RATE_NOTIFY, pb);

        // }
        // else if(msgId == ConstMsgId.SC.PlayerLoadingCompleteNotify)
        // {
        //     this._lum.getBehavior('BattleBehavior').emit(Event.CPT_MSG.LOADING_COMPLETE_NOTIFY, pb);

        // }
        // else if(msgId == ConstMsgId.SC.CreateTeamResponse)
        // {
        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.CREATE_TEAM_RESPONSE, pb);

        // } 
        // else if(msgId == ConstMsgId.SC.JoinTeamResponse)
        // {
        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.JOIN_TEAM_RESPONSE, pb);

        // }
        // else if(msgId == ConstMsgId.SC.JoinTeamNotify)
        // {

        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.JOIN_TEAM_NOTIFY, pb);

        // } 
        // else if(msgId == ConstMsgId.SC.LeaveTeamNotify)
        // {
        //     this._lum.getBehavior('LoginBehavior').emit(Event.CPT_MSG.LEAVE_TEAM_NOTIFY, pb);

        // }
        // else if (msgId == ConstMsgId.SC.WeeklySettleNotify)
        // {
        //     this._lum.getBehavior('LoginBehavior').setData(msgId, pb);
        // }                          
        
    }

    
    showWXUserinfoBtn()
    {
        this._lum.getBehavior('LoginBehavior').emit(Event.COM_MSG.SHOW_WX_LOGIN_BTN, {show:true});
        var that = this;
        let userinfoBtn = H5SDK.createUserInfoButton({
            type: 'text',
            text: '',
            style: {
              left: 0,
              top: 0,
              width: Common.wxWindowWidth,
              height: Common.wxwindowHeight,
              lineHeight: 40
            //   backgroundColor: '#00ff00',
            //   color: '#ffffff',
            //   textAlign: 'center',
            //   fontSize: 16,
            //   borderRadius: 4,
            }
        });
        
        userinfoBtn.onTap(function (res) {
            console.log('userinfoBtn.onTap:' +  JSON.stringify(res));
            if(res.hasOwnProperty('userInfo'))
            {
              userinfoBtn.hide()
              console.log('res.userInfo: ' + JSON.stringify(res.userInfo));
              that.loginWX(res.userInfo);

              that.playerInfoModel.setSelfWXPlayerInfo(res.userInfo);
              that._lum.getBehavior('LoginBehavior').emit(Event.COM_MSG.AUTH_OK,{});

              that.login(false);
          }
          else
          {
              console.log('userinfoBtn.onTap: auth fail'   );

          }

        });
    }

 



    loginWX(userInfo)
    {
        console.log('loginWX(userInfo):' + JSON.stringify(userInfo));        
        this._lum.getBehavior("LoginBehavior").hasLoginWX = true;
        console.log('loginWX(userInfo) 1:' );        
     
       
        console.log('loginWX(userInfo) 2:' );        
        //this.login(false);
  
    }

  
    onOpen()
    {
        // if (CC_WECHATGAME)
        // {
        //     this.getCode(false);
        // }
        // else
        // {
        //     this.login(false);
        // }
        console.log("onOpen")

 
        if(this.socketType ==  Define.SOCKET_TYPE.PLAZA)
        {
           // this._lum.getBehavior('LoginBehavior').login()

        }
        else if(this.socketType ==  Define.SOCKET_TYPE.GAME)
        {
            this._lum.getBehavior('BattleBehavior').onSocketLoginGameServer()

        }
        this._lum.getBehavior('LoginBehavior').emit(Event.SOCKET_MSG.OPEN, {});
        if( (this._socketConnectOkCallback && typeof(this._socketConnectOkCallback)==="function"))
        {
            this._socketConnectOkCallback()
            this._socketConnectOkCallback = null
        }

    }

    onReConnectStart()
    {


    }

    onConnectOk()
    {
       // this._lum.getBehavior('BattleBehavior').needCheckConnectGameing = true
        this._lum.getBehavior('BattleBehavior').emit(Event.SOCKET_MSG.RECONNECT_OK, {});

    }

    loadProto() 
    {
        var protoFiles = [
            ["resources/proto/client_request.proto", "./client_request.proto"],
            ["resources/proto/client_response.proto", "./client_response.proto"]  
        ];
        this._gameConnect.loadProto(protoFiles,this._onProtoLoaded.bind(this));
    }

    _onProtoLoaded()
    {
        this._gameConnect.open();
    }

    sendMsg(msg)
    {
        this._gameConnect.sendMsg(msg);
    }
   


}
