using System.Diagnostics;
using System.Net;
using System.Net.Http;

namespace Zerolauncher.Manager
{
    internal class LoginManager
    {
        //private static readonly HttpClient client = new HttpClient();

        public static async Task SendPostRequest()
        {
            var client = new HttpClient();
            client.DefaultRequestVersion = HttpVersion.Version20;
            client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower;
            var values = new Dictionary<string, string>
            {
                { "thing1", "hello" },
                { "thing2", "world" }
            };
            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);
        }

        public static async Task LoginTest()
        {
            var client = new HttpClient();
            client.DefaultRequestVersion = HttpVersion.Version20;
            client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower;
            var values = new Dictionary<string, string>
            {
                { "thing1", "hello" },
                { "thing2", "world" }
            };
            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);
        }

        public static void GameTest()
        {
            //Account account = new Account
            //{
            //    userName = "b1783488228",
            //    userPWD = "565656",
            //    serverId = "179"
            //};
            //SingleGame game = new SingleGame(account);
        }

        public static async Task DoLogin(SingleGame game)
        {
            var client = new HttpClient();
            string? need_web = null;
            client.Timeout = TimeSpan.FromSeconds(3);
            switch (game.account.providerId) 
            {
                case 0:
                    {
                        var values = new Dictionary<string, string>
                {
                    { "loginFrom", "uframe" },
                    { "postLoginHandler", "default" },
                    { "layoutSelfAdapting", "true" },
                    { "externalLogin", "qq" },
                    { "displayMode", "popup" },
                    { "layout", "vertical" },
                    { "appId", "www_home" },
                    { "mainDivId", "popup_login_div" },
                    { "includeFcmInfo", "false" },
                    { "userNameLabel", "4399用户名" },
                    { "userNameTip", "请输入4399用户名" },
                    { "welcomeTip", "欢迎回到4399" },
                    { "username", game.account.userName },
                    { "password", game.account.userPWD }
                };

                        var content = new FormUrlEncodedContent(values);
                        HttpResponseMessage? response = null;
                        try
                        {
                            response = await client.PostAsync("http://ptlogin.4399.com/ptlogin/login.do?v=1", content);
                        }
                        catch (Exception ex)
                        {
                            game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name}，消息：{ex.Message}");
                            need_web = $"http://web.4399.com/stat/togame.php?target=ddt&server_id=S{game.account.serverId}";
                            break;
                        }
                        var responseString = await response.Content.ReadAsStringAsync();
                        // eventHandles.__errorCallback('密码错误');
                        if (responseString.Contains("eventHandles.__errorCallback"))
                        {
                            game.Send($"{StaticHandleS.HintText} 登录异常:{responseString.Split("eventHandles.__errorCallback('")[1].Split("'")[0]}");
                            need_web = $"http://web.4399.com/stat/togame.php?target=ddt&server_id=S{game.account.serverId}";
                            break;
                        }
                        if(!game.Send($"{StaticHandleS.HintText} 登录成功,开始解析iframe")) return;
                    }
                    {
                        HttpResponseMessage? response = null;
                        try
                        {
                            response = await client.PostAsync("http://web.4399.com/stat/togame.php?target=ddt&server_id=S" + game.account.serverId, null);
                        }
                        catch (Exception ex)
                        {
                            game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name}，消息：{ex.Message}");
                            need_web = $"http://web.4399.com/stat/togame.php?target=ddt&server_id=S{game.account.serverId}";
                            break;
                        }
                        var responseString = await response.Content.ReadAsStringAsync();
                        if (!responseString.Contains("name=\"game_box\""))
                        {
                            game.Send($"{StaticHandleS.HintText} 解析异常:服务器返回数据不正确");
                            need_web = $"http://web.4399.com/stat/togame.php?target=ddt&server_id=S{game.account.serverId}";
                            break;
                        }
                        responseString = responseString.Split("name=\"game_box\"")[1].Split("src=\"")[1].Split("\"")[0];
                        try
                        {
                            response = await client.PostAsync(responseString, null);
                        }
                        catch (Exception ex)
                        {
                            game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name.Replace(" ", "_")}，消息：{ex.Message.Replace(" ", "_")}");
                            need_web = $"http://web.4399.com/stat/togame.php?target=ddt&server_id=S{game.account.serverId}";
                            break;
                        }
                        responseString = await response.Content.ReadAsStringAsync();
                        responseString = "http://" + response.RequestMessage.RequestUri.ToString().Split("/")[2] + "/" + responseString.Split("movie\" value='")[1].Split("'")[0];
                        Trace.WriteLine(responseString);
                        game.Send($"{StaticHandleS.GameSa} {responseString}");
                    }
                    break;
                default:
                    game.Send($"{StaticHandleS.HintText} 错误。未适配的运营商：{game.account.serverId}");
                    break;
            }
            client.Dispose();
            if (need_web == null) return;
            for (int i = 6; i > 0; i--)
            {
                await Task.Delay(1000);
                if (!game.Send($"{StaticHandleS.HintText} 自动登录失败，将在{i}后启用网页登录，关闭窗口取消")) { return; }
            }
            game.Send($"{StaticHandleS.UseBrowser} {need_web}");
        }
    }
}
