using PCUT.ViewModels;
using System;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace PCUT.Pages
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class UpsertUserPage : Page
    {
        private UpsertUserViewModel ViewModel { get; set; }
        public UpsertUserPage()
        {
            this.InitializeComponent();
            ViewModel = new UpsertUserViewModel();
            this.DataContext = ViewModel;
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            await ViewModel.LoadCategoriesAsync();
            if (e.Parameter is string userId && !string.IsNullOrEmpty(userId))
            {
                ViewModel.AddMode = false;
                await ViewModel.LoadUserAsync(userId);
            }
            else
            {
                ViewModel.AddMode = true;
            }
            ViewModel.Processed += OnUpsertProcessed;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            SaveButton.IsEnabled = false;
        }

        private void OnUpsertProcessed(object sender, UpsertProcessedEventArgs args)
        {
            if (args.Successed)
                Frame.GoBack();
            else
                SaveButton.IsEnabled = true;
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.GoBack();
        }

        private void TextBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
        {
            bool containsNonDigit = args.NewText.Any(ch => !char.IsDigit(ch));
            bool isTooLong = args.NewText.Length > 10;
            args.Cancel = containsNonDigit || isTooLong;
        }
    }
}
