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

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

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

        public Command CategoryCommand { get; }
        public Command ColorPickerCommand { get; }

        public SettingPage()
        {
            CategoryCommand = new Command(OnCategoryCommand);
            ColorPickerCommand = new Command(OnColorPickerCommand);
            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 OnColorPickerCommand(object o)
        {
            if (o is Color color)
            {
                PrimaryColor = Helper.WrapColorString(color.ToHex());
            }
        }
    }
}