using Android.Content;
using Android.Webkit;
using Pixiview.Droid.Renderers;
using Pixiview.Login;
using Pixiview.Utils;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace Pixiview.Droid.Renderers
{
    public class HybridWebViewRenderer : WebViewRenderer
    {
        public HybridWebViewRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement is HybridWebView webView)
            {
                Control.SetWebViewClient(new PixivWebViewClient(this));
                Control.LoadUrl(webView.Uri);
            }
        }

        private class PixivWebViewClient : FormsWebViewClient
        {
            private readonly HybridWebView webView;

            public PixivWebViewClient(HybridWebViewRenderer renderer) : base(renderer)
            {
                if (renderer.Element is HybridWebView view)
                {
                    webView = view;
                }
            }

            //public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)
            //{
            //    var uri = request.Url;
            //    if (uri.Host == "www.pixiv.net" && uri.Path == "/")
            //    {
            //        var client = new HttpClient(new HttpClientHandler { UseCookies = false })
            //        {
            //            BaseAddress = new Uri($"{uri.Scheme}://{uri.Host}"),
            //            Timeout = TimeSpan.FromSeconds(30)
            //        };
            //        var pathAndQuery = uri.Path;
            //        if (!string.IsNullOrEmpty(uri.Query))
            //        {
            //            pathAndQuery += "?" + uri.EncodedQuery;
            //        }
            //        using (var req = new HttpRequestMessage(
            //            request.Method == "POST" ? HttpMethod.Post : HttpMethod.Get,
            //            pathAndQuery))
            //        {
            //            var headers = req.Headers;
            //            if (request.RequestHeaders != null)
            //            {
            //                foreach (var h in request.RequestHeaders)
            //                {
            //                    headers.Add(h.Key, h.Value);
            //                }
            //            }

            //            using (var response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead).Result)
            //            {
            //                if (response.Headers.TryGetValues("x-userid", out var vals))
            //                {
            //                    Configs.SetUserId(string.Join(';', vals), true);
            //                }
            //            }
            //        }
            //        return true;
            //    }
            //    return base.ShouldOverrideUrlLoading(view, request);
            //}

            public override void OnPageFinished(Android.Webkit.WebView view, string url)
            {
                base.OnPageFinished(view, url);

                if (url == "https://www.pixiv.net/" ||
                    url == "https://www.pixiv.net/en/")
                {
                    var cookieManager = CookieManager.Instance;
                    var cookie = cookieManager.GetCookie(url);
                    Configs.SetCookie(cookie, true);

                    // user-id
                    if (cookie != null)
                    {
                        var index = cookie.IndexOf("PHPSESSID=");
                        if (index >= 0)
                        {
                            var session = cookie.Substring(index + 10);
                            index = session.IndexOf('_');
                            if (index > 0)
                            {
                                session = session.Substring(0, index);
                                Configs.SetUserId(session, true);
                            }
                        }
                    }

                    if (webView != null)
                    {
                        webView.OnLoginHandle();
                    }
                }
            }
        }
    }
}
