using System;
using System.Linq;
using System.Windows.Controls;
using C1.WPF.DataGrid;
using C1.WPF.DataGrid.Summaries;

namespace DataGridSamples
{
    /// <summary>
    /// Interaction logic for GrandTotalPage.xaml
    /// </summary>
    public partial class GrandTotal : UserControl
    {
        public GrandTotal()
        {
            InitializeComponent();

            grid.ItemsSource = Data.GetProducts();
        }

        private void grid_AutoGeneratingColumn(object sender, C1.WPF.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            Common.HandleColumnAutoGeneration(e);

            //Set built-in aggregate functions
            if (e.Property.Name == "StandardCost")
            {
                DataGridAggregate.SetAggregateFunctions(e.Column,
                    new DataGridAggregatesCollection
                    { 
                        new DataGridAggregateSum { ResultFormat = "SUM = {0}" },
                        new DataGridAggregateAvg { ResultFormat = "AVG = {0}" },
                    });
            }

            //Set custom aggregate functions
            if (e.Property.Name == "ProductModelID")
            {
                DataGridAggregate.SetAggregateFunctions(e.Column,
                    new DataGridAggregatesCollection
                    { 
                        new ModelsAggregate { CountItemsWhoseModelIsSpecified = false, ResultFormat = "Not specified = {0}" },
                        new ModelsAggregate { CountItemsWhoseModelIsSpecified = true, ResultFormat = "Specified = {0}" },
                    });
            }
        }

        private void grid_AutoGeneratedColumns(object sender, EventArgs e)
        {
            grid.Columns["ImageUrl"].DisplayIndex = 0;
        }
    }

    /// <summary>
    /// Custom aggregate function which computes the items whose model is specified or not.
    /// </summary>
    public class ModelsAggregate : DataGridAggregate
    {
        public bool CountItemsWhoseModelIsSpecified { get; set; }

        public override object Compute(DataGridRowCollection rows, C1.WPF.DataGrid.DataGridColumn column, bool recursive)
        {
            return rows.AsEnumerable(row => row.Type == DataGridRowType.Item &&
                                            row.DataItem is Product &&
                                            (((row.DataItem as Product).ProductModelID == 0 && !CountItemsWhoseModelIsSpecified) ||
                                             ((row.DataItem as Product).ProductModelID != 0 && CountItemsWhoseModelIsSpecified)), groupRow => recursive).Count();
        }
    }
}
