using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace InABox.DynamicGrid
{
    public class DefaultDynamicEditorGridLayout : DynamicEditorGridLayout
    {
        public override bool TabStripVisible
        {
            get { return Details.TabStripVisible; }
            set { Details.TabStripVisible = value; }
        }

        private DynamicTabControl Details;

        private double PageWidth = 0;
        private double PageHeight = 0;

        public override double TotalWidth => PageWidth;

        public override double TotalHeight => PageHeight;

        public DefaultDynamicEditorGridLayout()
        {
            Details = new DynamicTabControl();
            Details.VerticalAlignment = VerticalAlignment.Stretch;
            Details.HorizontalAlignment = HorizontalAlignment.Stretch;
            Details.Name = "Details";

            Details.SelectionChanged += Details_SelectionChanged;

            Content = Details;
        }

        public override void LoadPages(IEnumerable<IDynamicEditorPage> pages)
        {
            Details.Items.Clear();
            foreach (var page in pages.OrderBy(x => x.PageType).ThenBy(x => x.Order).ThenBy(x => x.Caption()))
            {
                var tab = new DynamicTabItem();
                tab.Header = page.Caption();
                tab.Content = page;
                Details.Items.Add(tab);

                var minSize = page.MinimumSize();
                PageWidth = Math.Max(PageWidth, minSize.Width);
                PageHeight = Math.Max(PageHeight, minSize.Height);
            }

            Details.SelectedItem = Details.Items.Count > 0 ? Details.Items[0] : null;
        }

        private bool bChanging;
        private void Details_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (bChanging || Details?.SelectedItem == null || e.OriginalSource != Details)
                return;


            bChanging = true;
            try
            {
                var tab = Details.SelectedItem as DynamicTabItem;
                if (tab is not null && tab.Content is IDynamicEditorPage page)
                {
                    SelectPage(page);
                }
            }
            finally
            {
                bChanging = false;
            }
        }
    }
}
