using System;
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.Extended;
using System.Collections;
using C1.Silverlight;

namespace GaugeBuilder
{
    public partial class CollectionWindow
        : C1Window
    {
        public CollectionWindow()
        {
            InitializeComponent();

            btnAdd.Click += new RoutedEventHandler(btnAdd_Click);
        }

        #region ** object model

        public event EventHandler<ElementRemovedEventArgs> Removed;
        public event EventHandler Added;

        public void AddItem(string name, object element, bool autoGenerateProperties, IList<PropertyAttribute> propDecorators)
        {
            TabItem tItem = new TabItem();
            tItem.Header = CreateHeader(name, element);

            // sets the property grid
            C1PropertyGrid pGrid = new C1PropertyGrid() { AutoGenerateProperties = autoGenerateProperties };

            pGrid.PropertyAttributes.AddRange(propDecorators);
            pGrid.SelectedObject = element;
            tItem.Content = pGrid;

            Tab.SelectedItem = tItem;
            Tab.Items.Add(tItem);
        }

        public void ClearItems()
        {
            Tab.Items.Clear();
        }

        #endregion

        #region ** private stuff

        private object CreateHeader(string name, object tag)
        {
            StackPanel stack = new StackPanel()
            {
                Orientation= Orientation.Horizontal
            };
            stack.Children.Add(new TextBlock()
            {
                Text = name
            });
            var btnRemove = new Button()
            {
                Style = (Style)Resources["RemoveButton"],
                Tag = tag
            };
            btnRemove.Click += new RoutedEventHandler(btnRemove_Click);
            stack.Children.Add(btnRemove);
            return stack;
        }

        void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            TabItem tItem = btn.FindParent<TabItem>();
            object tag = btn.Tag;
            if (Removed != null)
            {
                Removed(this, new ElementRemovedEventArgs() { RemovedElement = tag });
                Tab.Items.Remove(tItem);
            }
        }

        void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (Added != null)
            {
                Added(this, EventArgs.Empty);
            }
        }

        #endregion
    }

    public class ElementRemovedEventArgs
        : EventArgs
    {
        public object RemovedElement { get; set; }
    }
}
