using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace InvExplorer
{
    public class ColorCell : Grid
    {
        public ColorCell()
        {
            Width = Height = 15;
            Margin = new Thickness(4);
            HorizontalAlignment = HorizontalAlignment.Center;
            VerticalAlignment = VerticalAlignment.Center;
            LayoutUpdated += ColorCell_LayoutUpdated;
        }
        void ColorCell_LayoutUpdated(object sender, EventArgs e)
        {
            if (Background == null)
            {
                // look up the tree for a ViewModel data context
                for (FrameworkElement element = this; element != null; element = element.Parent as FrameworkElement)
                {
                    var vm = element.DataContext as ViewModel;
                    if (vm != null)
                    {
                        // get the index of this item in the current portfolio
                        var pf = vm.PortfoliosView.CurrentItem as Portfolio;
                        var item = this.DataContext as PortfolioItem;
                        var index = pf.Items.IndexOf(item);

                        // set the element color
                        var color = ViewModel.Palette[index];
                        Background = new SolidColorBrush(color);

                        // disconnect even handler and be done
                        LayoutUpdated -= ColorCell_LayoutUpdated;
                        break;
                    }
                }
            }
        }
    }
}
