using System.Windows;
using System.Windows.Controls;

using BS.Shared.Extensions;

namespace BeWo.View.Report.FLSReport
{
    public partial class FLSOverviewItem : UserControl
    {
        public static readonly DependencyProperty OverviewRowProperty = DependencyProperty.Register("OverviewRow", typeof(FLSOverviewRow), typeof(FLSOverviewItem), new UIPropertyMetadata(new FLSOverviewRow(), OverviewRowChanged));

        public FLSOverviewItem()
        {
            this.InitializeComponent();

            // itemListView.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
        }

        public FLSOverviewRow OverviewRow
        {
            get
            {
                return (FLSOverviewRow)this.GetValue(OverviewRowProperty);
            }

            set
            {
                this.SetValue(OverviewRowProperty, value);
            }
        }

        internal void InitItemSource(FLSOverviewRow row)
        {
            if (this.itemListView.ItemsSource == null)
            {
                this.itemListView.ItemsSource = row.DetailRows;
            }
        }

        private static void OverviewRowChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            FLSOverviewItem item = (FLSOverviewItem)obj;
            FLSOverviewRow row = (FLSOverviewRow)e.NewValue;
            item.InitItemSource(row);
        }

        private void Expander_Collapsed(object sender, RoutedEventArgs e)
        {
            var lExpander = (Expander)sender;
            var lPanel = lExpander.GetVisualParent<VirtualizingStackPanel>();
            if (lPanel != null)
            {
                lExpander.Dispatch(delegate
                        {
                            ScrollViewer lViewer = lPanel.ScrollOwner;
                            lPanel.ScrollOwner = null;
                            lPanel.ScrollOwner = lViewer;
                            lPanel.InvalidateMeasure();
                        });
            }
        }

        private void listview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.itemListView.SelectedItem != null)
            {
                (this.itemListView.ItemContainerGenerator.ContainerFromItem(this.itemListView.SelectedItem) as ListViewItem).IsSelected = false;
            }
        }
    }
}