using System;
using System.Collections.Generic;
using System.Windows;
using C1.Silverlight.DataGrid;
using C1.Silverlight.DataGrid.Summaries;

namespace C1DataGrid_Demo2010
{
    public partial class Grouping : System.Windows.Controls.UserControl
    {
        public Grouping()
        {
            InitializeComponent();
            grid.ItemsSource = Data.GetProducts();

            // populate the columns present in the C1DataGrid
            cmbColumns.ItemsSource = grid.Columns;
            foreach (var column in grid.Columns)
            {
                if (column.GroupState.Direction != DataGridSortDirection.None)
                {
                    cmbColumns.SelectedItem = column;
                    break;
                }
            }
            cmbColumns.SelectionChanged += (s, e) =>
            {
                grid.GroupBy(e.AddedItems[0] as DataGridColumn);
            };
        }

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

            if (e.Property.Name == "StandardCost")
            {
                DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
            }
        }


        private void grid_AutoGeneratedColumns(object sender, EventArgs e)
        {
            grid.Columns["StandardCost"].DisplayIndex = 6;
            grid.GroupBy(grid.Columns["ExpirationDate"]);
        }

        #region ** expand / collapse

        private void btnExpand_Click(object sender, RoutedEventArgs e)
        {
            grid.Rows.ExpandAll();
        }

        private void btnCollapse_Click(object sender, RoutedEventArgs e)
        {
            grid.Rows.CollapseAll();
        }

        #endregion

        #region ** new row

        private void grid_BeginningNewRow(object sender, DataGridBeginningNewRowEventArgs e)
        {
            Product product = (e.Item as Product);
            product.ExpirationDate = DateTime.Now.AddDays(7);
            product.Available = true;
            product.ImageUrl = "no_image_available_small.jpg";
        }

        #endregion
    }


    public class Models : List<Model>
    {
        public Models()
        {
            foreach (var model in Data.GetModels())
            {
                Add(model);
            }
        }
    }
}
