using System;
using System.Collections.Generic;
using System.Text;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;

namespace nft.ui.docking {
    class DockPanelCustomizer {

        private class CustomDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory {
            private DockPanelExtender.IDockPaneCaptionFactory original;
            public CustomDockPaneCaptionFactory(DockPanel dockPanel) {
                this.original = dockPanel.Extender.DockPaneCaptionFactory;
            }

            public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) {
                DockPaneCaptionBase cap = original.CreateDockPaneCaption(pane);
                PropertyInfo pi = cap.GetType().GetProperty("ButtonAutoHide", BindingFlags.NonPublic | BindingFlags.Instance);
                Control btn = pi.GetValue(cap, null) as Control;
                btn.Tag = pane;
                btn.VisibleChanged += new EventHandler(btn_VisibleChanged);
                return cap;
            }

            void btn_VisibleChanged(object sender, EventArgs e) {
                Control c = sender as Control;
                DockPane pane = c.Tag as DockPane;
                if (c.Visible && pane != null) {
                    // There are possibility of that this DockPane has several DockContents as tab pages.
                    // So we need to check an option for all child DockContents.
                    IEnumerator<IDockContent> en = pane.Contents.GetEnumerator();
                    while (en.MoveNext()) {
                        DefaultDockForm form = en.Current as DefaultDockForm;
                        if (form != null && form.Holder.HasOption(StyleOption.NoShrink)) {
                            c.Visible = false;
                        }
                    }

                }
            }
        }

        public static void SetupFactories(DockPanel dockPanel) {
            dockPanel.Extender.DockPaneCaptionFactory = new CustomDockPaneCaptionFactory(dockPanel);
        }

        public class CustomDockPaneCaption : DockPaneCaptionBase {
            internal protected CustomDockPaneCaption(DockPane pane)
                : base(pane) {
            }

            protected override int MeasureHeight() {
                throw new NotImplementedException();
            }
        }
    }
}
