using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sonex.UserControls.DataGridView
{
    public sealed partial class DataGridView
    {
        private void UpdateFooterTextSelected()
        {
            _FooterText2.Text = $"Selected: {_SelectedRows?.CountSelected().ToString("N0") ?? "0"} rows";
            decimal sum = 0;
            foreach (var column in _Columns)
            {
                if (column.isSelected == false) continue;
                decimal? s = GetSelectedSum(column);
                if (s != null)
                    sum += s.Value;

            }
            _FooterText3.Text = $"Sum: {sum.ToString("N2")}";


        }

        public decimal? GetSelectedSum(Column column)
        {
            try
            {
                if (_ItemsSourceFiltred == null) return null;
                if (column?.PropertyInfo == null) return null;
                if (_SelectedRows == null || _SelectedRows.CountSelected() == 0) return null;

                var t = Nullable.GetUnderlyingType(column.PropertyInfo.PropertyType)
                        ?? column.PropertyInfo.PropertyType;

                if (!IsNumericType(t))
                    return null;

                decimal sum = 0m;
                bool hasValue = false;

                foreach (var rowIndex in _SelectedRows)
                {
                    if (rowIndex < 0 || rowIndex >= _ItemsSourceFiltred.Count)
                        continue;

                    var item = _ItemsSourceFiltred[rowIndex];
                    if (item == null) continue;

                    var value = column.PropertyInfo.GetValue(item);
                    if (value == null) continue;

                    sum += Convert.ToDecimal(value);
                    hasValue = true;
                }

                return hasValue ? sum : null;
            }
            catch (Exception e)
            {
                return null;
            }

        }
    }
}
