using System.Collections.Generic;
using System.Runtime.InteropServices;
using Decal.Interop.Controls;
using Decal.Interop.Inject;

namespace Decal.DecalControls
{
    [ComVisible(true)]
    [Guid("ED14E7C5-11BE-4DFD-9829-873AB6BE3CFC")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces("Decal.Interop.Controls.INotebookEvents\0\0")]
    [ProgId("DecalControls.Notebook")]
    public class NotebookImpl : ControlBase, INotebook
    {
        public event INotebookEvents_DestroyEventHandler Destroy;
        public event INotebookEvents_ChangeEventHandler Change;

        private struct Page
        {
            public string Text;
            public IControl Client;
        }

        private readonly List<Page> _pages = new List<Page>();
        private int _activeTab;

        public void AddPage(string strText, IControl pClient)
        {
            _pages.Add(new Page { Text = strText ?? "", Client = pClient });
            Invalidate();
        }

        public int ActiveTab
        {
            get => _activeTab;
            set
            {
                if (value >= 0 && value < _pages.Count && value != _activeTab)
                {
                    _activeTab = value;
                    Invalidate();
                    Change?.Invoke(ID, _activeTab);
                }
            }
        }

        public string PageText
        {
            get => (_activeTab >= 0 && _activeTab < _pages.Count) ? _pages[_activeTab].Text : "";
            set
            {
                if (_activeTab >= 0 && _activeTab < _pages.Count)
                {
                    var page = _pages[_activeTab];
                    page.Text = value ?? "";
                    _pages[_activeTab] = page;
                    Invalidate();
                }
            }
        }

        protected override void OnDestroy() => Destroy?.Invoke(ID);
    }
}
