using pomelo.area;
using pomelo.connector;
using pomelo.login;
using Pomelo.DotNetClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XmdsCommon.EditorData;

namespace XmdsBattleClientBot.Bot
{
    // 游戏服相关 //
    partial class BotClient
    {
        static String s_robotPwd = "9cbf8a4dcb8e30682b927f352d6559a0";
        static int s_robotOS = 1984579230;
        static String s_robotModle = "Robot";
        static String s_robotMac = "lnkj89adasfadfaser2345234523458789dfu";


        public EntryResponse LastEntryResponse { get; private set; }
        public GetRandomNameResponse LastGetRandomNameResponse { get; private set; }
        public CreatePlayerResponse LastCreatePlayerResponse { get; private set; }
        public BindPlayerResponse LastBindPlayerResponse { get; private set; }
        public pomelo.player.Player PlayerData { get; private set; }
        public string PlayerUUID { get { return (PlayerData != null ? PlayerData.uid : null); } }


        private dynamic getServer(string json, int serverId)
        {
            dynamic arr = SimpleJson.SimpleJson.DeserializeObject(json);
            foreach (dynamic arr1 in arr)
            {
                foreach (dynamic arr2 in arr1)
                {
                    string area = arr2.Key;
                    foreach (dynamic arr3 in arr2.Value)
                    {
                        int sid = (int)arr3[0];
                        if (sid == serverId)
                        {
                            return new
                            {
                                sid = sid,
                                name = (string)arr3[1],
                                ip = (string)arr3[2],
                                port = (int)arr3[3]
                            };
                        }
                    }
                }
            }
            return null;
        }


        public void login(Action on_login, Action<Exception> on_error = null)
        {
           int serverId = Config.ServerID;
            Client.GateSocket.loginHandler.loginRequest(2, config.Appid.ToString(), Account, s_robotPwd, "999", s_robotOS, s_robotModle, s_robotMac, config.ClientVersion, 
                config.Channel.ToString(),  (PomeloException exception, LoginResponse res) =>
            {
                if (res != null)
                {
					this.Sign = res.token;
					this.GetAreaServersAndStartGame(Account, on_login, on_error);
					//Sign = res.token;
					//dynamic server = getServer(res.board, serverId);
					//if (server != null)
					//{
					//	ServerId = server.sid;
					//	Host = server.ip;
					//	Port = server.port;
					//	on_login();
					//}
					//else
					//{
					//	MessageBox.Show("AppId : " + Config.Appid + @" 登录不存在服务器ID : " + serverId);
					//}
				}
                else
                {
                    if (on_error != null)
                    {
                        on_error(exception);
                    }
                    else
                    {
                        MessageBox.Show(exception.Message);
                    }
                }
            });
        }

		/** 获取服务器列表 */
		public void GetAreaServersAndStartGame(String uid, Action on_login, Action<Exception> on_error = null)
		{
			
			int serverId = Config.ServerID;
			if(serverId == -1)
			{
				int uidNum = Convert.ToInt32(uid.Substring(6));
				serverId = 10001 + uidNum / 30;
			}

			Client.GateSocket.loginHandler.getAreaServerInfoRequest(80, 1,(PomeloException exception, GetAreaServerInfoResponse res) =>
			{
				if (res != null)
				{
					ServerInfo findSrv = null;
					foreach (ServerInfo srvInfo in res.svrInfos)
					{
						if(srvInfo.serverid == serverId)
						{
							findSrv = srvInfo;
							break;
						}
					}
					if (findSrv != null)
					{
						ServerId = findSrv.serverid;
						Host = findSrv.serverhost;
						Port = findSrv.serverport;
						on_login();
					}
					else
					{
						MessageBox.Show("AppId : " + Config.Appid + @" 登录不存在服务器ID : " + serverId);
					}
				}
				else
				{
					if (on_error != null)
					{
						on_error(exception);
					}
						else
					{
						MessageBox.Show(exception.Message);
					}
				}
			});
		}


        public void register(Action on_login, Action<Exception> on_error = null)
        {
           
            Client.GateSocket.loginHandler.registerRequest(config.Appid, Account, s_robotPwd, 999 /*config.Channel*/, s_robotOS,  s_robotModle, s_robotMac, 
                config.ClientVersion,  (PomeloException exception, RegisterResponse res) =>
            {
                if (res != null)
                {
					this.Sign = res.token;
					this.GetAreaServersAndStartGame(Account, on_login, on_error);
				//    int serverId = Config.ServerID;
				//    Sign = res.token;
				//    dynamic server = getServer(res.board, serverId);
				//    if (server != null)
				//    {
				//        ServerId = server.sid;
				//        Host = server.ip;
				//        Port = server.port;
				//        on_login();
				//    }
				//    else
				//    {
				//        if (on_error != null)
				//        {
				//            log.Error("AppId : " + Config.Appid + @" 注册不存在服务器ID : " + serverId);
				//        }
				//        else
				//        {
				//            MessageBox.Show("AppId : " + Config.Appid + @" 注册不存在服务器ID : " + serverId);
				//        }
				//    }
				}
				else
                {
                    if (on_error != null)
                    {
                        on_error(exception);
                    }
                    else
                    {
                        MessageBox.Show(exception.Message);
                    }
                }
            });
        }

        public void gate_EnterServer(Action<EntryResponse> callback, Action<Exception> error = null)
        {
            string sign = this.Sign;
            ulong time = 0;

            string mac = config.MacAddr;
            int ostype = config.OSType;
            string region = config.ClientRegion;
            string channel = config.Channel.ToString();
            string version = config.ClientVersion;
            
            this.Client.LoginHandler.Request_EntryServerNew(Account, sign, time, ServerId, Host, Port, mac, ostype, region, channel, version, (EntryResponse msg) =>
            {
                this.LastEntryResponse = msg;
                callback(msg);
            }, (err) =>
            {
                log.Error(err.Message);
                if (error != null) error.Invoke(err);
            });
        }
        public void gate_ReEnterServer(Action<EntryResponse> callback, Action<Exception> error = null)
        {
           gate_EnterServer(callback, error);
        }

        public void gate_GetRandomName(int pro, Action<GetRandomNameResponse> callback, Action<Exception> error = null)
        {
            this.Client.LoginHandler.Request_RandomName(pro, (GetRandomNameResponse msg) =>
            {
                this.LastGetRandomNameResponse = msg;
                callback(msg);
            }, (err) =>
            {
                log.Error(err.Message, err);
                if (error != null) error.Invoke(err);
            });
        }

        public void gate_CreateRole(int pro, string name, Action<CreatePlayerResponse> callback, Action<Exception> error = null)
        {
            this.Client.LoginHandler.Request_CreateRole(pro, name, 0, (CreatePlayerResponse msg) =>
            {
                this.LastCreatePlayerResponse = msg;
                callback(msg);
            }, (err) =>
            {
                log.Error(err.Message, err);
                if (error != null) error.Invoke(err);
            });
        }

        public void gate_BindPlayer(string playerId, Action<BindPlayerResponse> callback, Action<Exception> error = null)
        {
            this.Client.LoginHandler.Request_BindPlayer(playerId, (BindPlayerResponse msg) =>
            {
                this.LastBindPlayerResponse = msg;
                this.PlayerData = msg.s2c_player;
                callback_gate_BindPlayer(msg);
                callback(msg);
                //成功进入场景标记
                this._IsInScene = true;

            }, (err) =>
            {
                log.Error(err.Message, err);
                if (error != null) error.Invoke(err);
            });
        }

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

        private void callback_gate_BindPlayer(BindPlayerResponse msg)
        {
            this.CurrentSceneType = (CommonAI.Data.SceneType)msg.s2c_sceneType;
            this.CurrentQuestManager = new QuestManager(this);
            this.CurrentInventories = new InventoryManager(this);
            //this.CurrentChatManager = new ChatManager(this);
        }

        //---------------------------------------------------------------------------------------------------------------
    }
}