using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight.FlexGrid;

namespace UnboundConditionalFormatting
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            var flex = new C1FlexGrid();
            flex.CellFactory = new ConditionalFormattingFactory();
            LayoutRoot.Children.Add(flex);

            var list = Product.GetProducts(100);

#if BOUNDMODE
            flex.ItemsSource = list;
#else            
            foreach (var pi in typeof(Product).GetProperties())
            {
                var c = new Column();
                c.Header = pi.Name;
                c.DataType = pi.PropertyType;
                if (pi.PropertyType == typeof(double))
                {
                    c.Format = "n0";
                }
                flex.Columns.Add(c);
            }
            foreach (var p in list)
            {
                var r = new Row();
                flex.Rows.Add(r);
                foreach (var c in flex.Columns)
                {
                    var pi = typeof(Product).GetProperty(c.Header);
                    r[c] = pi.GetValue(p, null);
                }
            }
        }
#endif
    }
    class ConditionalFormattingFactory : CellFactory
    {
        // create brushes used to indicate low and high values
        static Brush _brLowValue = new SolidColorBrush(Colors.Red);
        static Brush _brHighValue = new SolidColorBrush(Colors.Green);

        // overridden to apply the custom brushes based on the cell value
        public override void ApplyCellStyles(C1FlexGrid grid, CellType cellType, CellRange range, Border bdr)
        {
            // we are interested only in data cells (no headers)
            if (cellType == CellType.Cell)
            {
                // we are interested in double values only
                var col = grid.Columns[range.Column];
                if (col.DataType == typeof(double))
                {
                    // get the cell value
                    var value = (double)grid[range.Row, col];

                    // apply formatting if value is out of range
                    if (value < 10 || value > 100)
                    {
                        var tb = bdr.Child as TextBlock;
                        if (tb != null)
                        {
                            tb.Foreground = value < 10 ? _brLowValue : _brHighValue;
                        }
                    }
                }
            }
        }
    }
}
