using System;
using System.Diagnostics;

namespace Sonex.Client.Controls.DataGridView
{
    // Odpowiedzialnosc pliku: aktualizacja stopki (liczniki i sumowanie zaznaczenia).
    public sealed partial class DataGridView
    {
        private void UpdateFooterTextSelected()
        {
            var totalRows = _ItemsSource?.Count ?? 0;
            var filteredRows = _ItemsSourceFiltred?.Count ?? 0;

            _FooterText1.Text = $"Rows: {filteredRows:N0} / {totalRows:N0}";
            _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)
            {
                Debug.Write(e);
                return null;
            }

        }
    }
}
