using System;
using Pixiview.Resources;
using Pixiview.UI;
using Pixiview.Utils;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace Pixiview
{
    public partial class OptionPage : AdaptedPage
    {
        public static readonly BindableProperty IsOnR18Property = BindableProperty.Create(
            nameof(IsOnR18), typeof(bool), typeof(OptionPage));
        public static readonly BindableProperty SyncFavTypeProperty = BindableProperty.Create(
            nameof(SyncFavType), typeof(int), typeof(OptionPage), -1);
        public static readonly BindableProperty IsProxiedProperty = BindableProperty.Create(
            nameof(IsProxied), typeof(bool), typeof(OptionPage));
        public static readonly BindableProperty HostProperty = BindableProperty.Create(
            nameof(Host), typeof(string), typeof(OptionPage));
        public static readonly BindableProperty PortProperty = BindableProperty.Create(
            nameof(Port), typeof(string), typeof(OptionPage));
        public static readonly BindableProperty CookieProperty = BindableProperty.Create(
            nameof(Cookie), typeof(string), typeof(OptionPage));

        public bool IsOnR18
        {
            get => (bool)GetValue(IsOnR18Property);
            set => SetValue(IsOnR18Property, value);
        }
        public int SyncFavType
        {
            get => (int)GetValue(SyncFavTypeProperty);
            set => SetValue(SyncFavTypeProperty, value);
        }
        public bool IsProxied
        {
            get => (bool)GetValue(IsProxiedProperty);
            set => SetValue(IsProxiedProperty, value);
        }
        public string Host
        {
            get => (string)GetValue(HostProperty);
            set => SetValue(HostProperty, value);
        }
        public string Port
        {
            get => (string)GetValue(PortProperty);
            set => SetValue(PortProperty, value);
        }
        public string Cookie
        {
            get => (string)GetValue(CookieProperty);
            set => SetValue(CookieProperty, value);
        }

        public OptionPage()
        {
            BindingContext = this;
            InitializeComponent();

            optionFavSync.Items = new[]
            {
                ResourceHelper.SyncNo,
                ResourceHelper.SyncPrompt,
                ResourceHelper.SyncAuto,
            };
            SyncFavType = 0;
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            IsOnR18 = Configs.IsOnR18;
            SyncFavType = (int)Configs.SyncFavType;
            var proxy = Configs.Proxy;
            if (proxy != null)
            {
                IsProxied = true;
                Host = proxy.Address.Host;
                Port = proxy.Address.Port.ToString();
            }
            else
            {
                IsProxied = false;
                Host = Preferences.Get(Configs.HostKey, string.Empty);
                Port = Preferences.Get(Configs.PortKey, string.Empty);
            }

            Cookie = Configs.Cookie;
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();

            var r18 = IsOnR18;
            var syncType = SyncFavType;
            var proxied = IsProxied;

            if (Configs.IsOnR18 != r18)
            {
                Preferences.Set(Configs.IsOnR18Key, r18);
                Configs.IsOnR18 = r18;
#if LOG
                App.DebugPrint($"r-18 filter: {r18}");
#endif
            }

            if ((int)Configs.SyncFavType != syncType)
            {
                Preferences.Set(Configs.SyncFavTypeKey, syncType);
                Configs.SyncFavType = (SyncType)syncType;
#if LOG
                App.DebugPrint($"favorite sync type changed to {Configs.SyncFavType}");
#endif
            }

            var proxy = Configs.Proxy;
            var h = Host?.Trim();
            _ = int.TryParse(Port, out int pt);
            if (proxied)
            {
                if (proxy == null ||
                    proxy.Address.Host != h ||
                    proxy.Address.Port != pt)
                {
                    Preferences.Set(Configs.IsProxiedKey, true);
                    Preferences.Set(Configs.HostKey, h);
                    if (pt > 0)
                    {
                        Preferences.Set(Configs.PortKey, pt);
                    }
                    if (!string.IsNullOrEmpty(h) && pt > 0)
                    {
                        Configs.Proxy = new System.Net.WebProxy(h, pt);
#if LOG
                        App.DebugPrint($"set proxy to: {h}:{pt}");
#endif
                    }
                }
            }
            else
            {
                Preferences.Set(Configs.IsProxiedKey, false);
                Preferences.Set(Configs.HostKey, h);
                if (pt > 0)
                {
                    Preferences.Set(Configs.PortKey, pt);
                }
                if (proxy != null)
                {
                    Configs.Proxy = null;
#if LOG
                    App.DebugPrint("clear proxy");
#endif
                }
            }

            var cookie = Cookie;
            if (Configs.Cookie != cookie)
            {
                Configs.SetCookie(cookie, true);
                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 LOG
                        App.DebugPrint($"cookie changed, user id: {session}");
#endif
                    }
                }
            }
        }

        private async void ShareCookie_Clicked(object sender, EventArgs e)
        {
            await Share.RequestAsync(new ShareTextRequest
            {
                Text = Cookie
            });
        }
    }
}
