using System;
using Foundation;
using Pixiview.iOS.Renderers;
using Pixiview.Login;
using Pixiview.Utils;
using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace Pixiview.iOS.Renderers
{
    public class HybridWebViewRenderer : WkWebViewRenderer
    {
        public HybridWebViewRenderer() : this(new WKWebViewConfiguration())
        {
        }

        public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
        {
        }

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.NewElement is HybridWebView webView)
            {
                string url = webView.Uri;
                //Configuration.SetUrlSchemeHandler
                CustomUserAgent = webView.UserAgent;
                NavigationDelegate = new PixivNavigationDelegate(webView);

                LoadRequest(new NSUrlRequest(NSUrl.FromString(url)));
            }
        }

        private class PixivNavigationDelegate : WKNavigationDelegate
        {
            private readonly HybridWebView hybridWebView;

            public PixivNavigationDelegate(HybridWebView hybrid)
            {
                hybridWebView = hybrid;
            }

            public override void DecidePolicy(WKWebView webView, WKNavigationResponse navigationResponse, Action<WKNavigationResponsePolicy> decisionHandler)
            {
                var url = webView.Url;
                if (url.Host == "www.pixiv.net" && url.Path == "/")
                {
                    if (navigationResponse.Response is NSHttpUrlResponse response)
                    {
                        if (response.AllHeaderFields.TryGetValue(new NSString("x-userid"), out var val))
                        {
                            Configs.SetUserId(val.ToString(), true);
                        }
                    }
                }

                decisionHandler(WKNavigationResponsePolicy.Allow);
            }

            public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
            {
                var url = webView.Url;
                if (url.Host == "www.pixiv.net" && (url.Path == "/" || url.Path == "/en/"))
                {
                    var store = webView.Configuration.WebsiteDataStore.HttpCookieStore;
                    var result = await Configs.RequestCookieContainer(store);

                    if (result && hybridWebView != null)
                    {
                        hybridWebView.OnLoginHandle();
                    }
                }
            }
        }
    }
}
