using Billing.Themes;
using Billing.UI;
using System.Globalization;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace Billing.Views
{
    public partial class SettingPage : BillingPage
    {
        private static readonly BindableProperty VersionProperty = BindableProperty.Create(nameof(Version), typeof(string), typeof(SettingPage));
        private static readonly BindableProperty PrimaryColorProperty = BindableProperty.Create(nameof(PrimaryColor), typeof(string), typeof(SettingPage));

        public string Version => (string)GetValue(VersionProperty);
        public string PrimaryColor
        {
            get => (string)GetValue(PrimaryColorProperty);
            set => SetValue(PrimaryColorProperty, value);
        }

        public Command CategoryCommand { get; }

        public SettingPage()
        {
            CategoryCommand = new Command(OnCategoryCommand);
            InitializeComponent();

            var (main, build) = Definition.GetVersion();
            SetValue(VersionProperty, $"{main} ({build})");
        }

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

            //SetValue(VersionProperty, $"{AppInfo.VersionString} ({AppInfo.BuildString})");
            var colorString = Preferences.Get(Definition.PrimaryColorKey, Helper.DEFAULT_COLOR);
            PrimaryColor = Helper.WrapColorString(colorString);
        }

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

            var color = PrimaryColor;
            Preferences.Set(Definition.PrimaryColorKey, color);
            Light.Instance.RefreshColor(Color.FromHex(color));
        }

        private async void OnCategoryCommand()
        {
            if (Tap.IsBusy)
            {
                return;
            }
            using (Tap.Start())
            {
                var page = new CategoryPage();
                await Navigation.PushAsync(page);
            }
        }

        private void ColorPicker_ColorChanged(object sender, Color e)
        {
            PrimaryColor = Helper.WrapColorString(e.ToHex());
        }
    }
}