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

namespace Decal.DecalControls
{
    [ComVisible(true)]
    [Guid("8E8F88D2-AA47-474E-9DB7-912D49C8BE9D")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces("Decal.Interop.Controls.IEditEvents\0\0")]
    [ProgId("DecalControls.Edit")]
    public class EditImpl : ControlBase, IEdit
    {
        public event IEditEvents_DestroyEventHandler Destroy;
        public event IEditEvents_BeginEventHandler Begin;
        public event IEditEvents_ChangeEventHandler Change;
        public event IEditEvents_EndEventHandler End;

        private string _text = "";
        private int _caret;
        private int _selStart, _selEnd;
        private IImageCache _background;
        private IFontCache _font;
        private int _textColor;

        public string Text
        {
            get => _text;
            set
            {
                _text = value ?? "";
                _caret = _text.Length;
                Invalidate();
                Change?.Invoke(ID, _text);
            }
        }

        public int Caret { get => _caret; set { _caret = value; Invalidate(); } }

        public void Select(int nStart, int nEnd)
        {
            _selStart = nStart;
            _selEnd = nEnd;
            Invalidate();
        }

        public string SelectedText
        {
            get
            {
                if (_selStart >= 0 && _selEnd > _selStart && _selEnd <= _text.Length)
                    return _text.Substring(_selStart, _selEnd - _selStart);
                return "";
            }
            set
            {
                if (_selStart >= 0 && _selEnd > _selStart && _selEnd <= _text.Length)
                {
                    _text = _text.Remove(_selStart, _selEnd - _selStart).Insert(_selStart, value ?? "");
                    _caret = _selStart + (value?.Length ?? 0);
                    _selStart = _selEnd = 0;
                    Invalidate();
                    Change?.Invoke(ID, _text);
                }
            }
        }

        public IImageCache Background { get => _background; set { _background = value; Invalidate(); } }
        public IFontCache Font { get => _font; set { _font = value; Invalidate(); } }
        public int TextColor { get => _textColor; set { _textColor = value; Invalidate(); } }

        public void SetMargins(int nX, int nY) { }

        public void Capture()
        {
            if (_site != null)
            {
                ((ILayerSite)(object)_site).CaptureKeyboard();
                Begin?.Invoke(ID);
            }
        }

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