using Elwig.Helpers;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Elwig.Dialogs {
    public partial class DeleteMemberDialog : Window {

        protected string[] NameParts;

        public bool DeleteAreaComs { get; set; }
        public bool DeleteDeliveries { get; set; }
        public bool DeletePaymentData { get; set; }

        public DeleteMemberDialog(int mgnr, string name, int numAreaComs, int numDeliveries, int numCredits) {
            NameParts = name.ToLower().Split(' ').Where(p => p.Length > 0).Append($"{mgnr}").ToArray();
            InitializeComponent();
            Title += " - " + name;
            AreaComInput.IsEnabled = numAreaComs != 0;
            AreaComInput.Content += $" ({numAreaComs:N0})";
            DeliveryInput.IsEnabled = numDeliveries != 0;
            DeliveryInput.Content += $" ({numDeliveries:N0})";
            PaymentInput.IsEnabled = numCredits != 0;
            PaymentInput.Content += $" ({numCredits:N0})";
        }

        private void NameInput_TextChanged(object sender, TextChangedEventArgs evt) {
            Update();
        }

        private void CheckBox_Changed(object sender, RoutedEventArgs evt) {
            Update();
        }

        private static void UpdateCheckBox(CheckBox cb) {
            if (cb.IsEnabled && cb.IsChecked != true) {
                ControlUtils.SetInputInvalid(cb);
            } else {
                ControlUtils.ClearInputState(cb);
            }
        }

        private void Update() {
            var t = NameInput.Text.ToLower().Split(' ');
            var nameValid = NameParts.All(t.Contains);
            UpdateCheckBox(AreaComInput);
            UpdateCheckBox(DeliveryInput);
            UpdateCheckBox(PaymentInput);
            if (!nameValid) {
                ControlUtils.SetInputInvalid(NameInput);
            } else {
                ControlUtils.ClearInputState(NameInput);
            }
            ConfirmButton.IsEnabled =
                (!AreaComInput.IsEnabled || DeleteAreaComs) &&
                (!DeliveryInput.IsEnabled || DeleteDeliveries) &&
                (!PaymentInput.IsEnabled || DeletePaymentData) &&
                nameValid;
        }

        private void ConfirmButton_Click(object sender, RoutedEventArgs evt) {
            DialogResult = true;
            Close();
        }
    }
}
