using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Runtime.ConstrainedExecution;
using System.Text.RegularExpressions;

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:
                    game.Send($"{StaticHandleS.HintText} 尝试登玩家{game.account.nickName}到{ServicesStaticInfo.ServicesName[game.account.providerId]}的1服");
                    {
                        HttpResponseMessage response;
                        try
                        {
                            response = await client.GetAsync("http://180.97.189.249:2023");
                        }
                        catch (Exception ex)
                        {
                            game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name}，消息：{ex.Message}");
                            need_web = $"http://180.97.189.249:2023";
                            break;
                        }
                        var responseString = await response.Content.ReadAsStringAsync();
                        int count = 0;
                        while (responseString.Contains("adfwkey"))
                        {
                            if (count++ <= 10)
                            {
                                game.Send($"{StaticHandleS.HintText} 网络被服务器拦截多次，请重试或联系管理员");
                                need_web = $"http://180.97.189.249:2023";
                                break;
                            }
                            var key = responseString.Split("adfwkey=")[1].Split("\"", 2)[0];
                            game.Send($"{StaticHandleS.HintText} 被服务验证拦截-验证码key:{key}");
                            try
                            {
                                response = await client.GetAsync("http://180.97.189.249:2023");
                            }
                            catch (Exception ex)
                            {
                                game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name}，消息：{ex.Message}");
                                need_web = $"http://180.97.189.249:2023";
                                break;
                            }
                            responseString = await response.Content.ReadAsStringAsync();
                        }
                    }
                    {
                        var values = new Dictionary<string, string>
                        {
                            { "lUsername", game.account.userName },
                            { "lPassword", game.account.userPWD }
                        };
                        var content = new FormUrlEncodedContent(values);
                        HttpResponseMessage response;
                        try
                        {
                            response = await client.PostAsync("http://180.97.189.249:2023/form/login.php", content);
                        }
                        catch (Exception ex)
                        {
                            game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name}，消息：{ex.Message}");
                            need_web = $"http://180.97.189.249:2023";
                            break;
                        }
                        var responseString = await response.Content.ReadAsStringAsync();
                        JObject jsonObj = JObject.Parse(responseString);
                        game.Send($"{StaticHandleS.HintText} {jsonObj["title"]}");
                        game.Send($"{StaticHandleS.HintText} {jsonObj["content"]}");
                        if ((int)jsonObj["type"] != 0)
                        {
                            need_web = $"http://180.97.189.249:2023";
                            break;
                        }
                        if(!game.Send($"{StaticHandleS.HintText} 登录成功,开始解析iframe")) return;
                    }
                    {
                        HttpResponseMessage response;
                        try
                        {
                            response = await client.GetAsync("http://180.97.189.249:2023/Play/Play.php?id=1");
                        }
                        catch (Exception ex)
                        {
                            game.Send($"{StaticHandleS.HintText} 网络发生错误，类型：{ex.GetType().Name}，消息：{ex.Message}");
                            need_web = $"http://180.97.189.249:2023";
                            break;
                        }
                        var responseString = await response.Content.ReadAsStringAsync();
                        if (!responseString.Contains("var swfPath"))
                        {
                            game.Send($"{StaticHandleS.HintText} 解析异常:服务器返回数据不正确1");
                            need_web = $"http://180.97.189.249:2023";
                            break;
                        }
                        //responseString = "" + responseString.Split("var swfPath")[1].Split("};")[0] + "};";
                        string pattern = @"var swfPath = ""(.*?)"";(.*?){(.*?)};";
                        Match match = Regex.Match(responseString, pattern, RegexOptions.Singleline);

                        if (!match.Success) 
                        {
                            game.Send($"{StaticHandleS.HintText} 解析异常:服务器返回数据不正确2");
                            //Trace.WriteLine($"---------{responseString}|");
                            need_web = $"http://180.97.189.249:2023";
                            break;
                        }
                        string url = match.Groups[1].Value;
                        string parameters = match.Groups[3].Value;

                        string patternParams = @"(\w+): ""(.*?)""";
                        MatchCollection matches = Regex.Matches(parameters, patternParams);

                        url += "?";
                        foreach (Match m in matches)
                        {
                            url += $"{m.Groups[1].Value}={WebUtility.UrlEncode(m.Groups[2].Value)}&";
                        }
                        url = url.TrimEnd('&');
                        Trace.WriteLine(url);
                        game.Send($"{StaticHandleS.GameSa} {url}");
                    }
                    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}");
        }
    }
}
