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

namespace Decal.DecalControls
{
    [ComVisible(true)]
    [Guid("8FC80D21-1731-4816-9AD3-B0364D5F2C27")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces("Decal.Interop.Controls.IScrollerEvents\0\0")]
    [ProgId("DecalControls.Scroller")]
    public class ScrollerImpl : ControlBase, IScroller
    {
        public event IScrollerEvents_DestroyEventHandler Destroy;
        public event IScrollerEvents_ChangeEventHandler Change;

        private tagSIZE _area;
        private tagPOINT _offset;
        private tagSIZE _increments = new tagSIZE { cx = 1, cy = 1 };
        private bool _horizontalEnabled = true;
        private bool _verticalEnabled = true;

        public tagSIZE Viewport
        {
            get
            {
                var pos = Position;
                return new tagSIZE { cx = pos.right - pos.left, cy = pos.bottom - pos.top };
            }
        }

        public tagSIZE Area { get => _area; set { _area = value; Invalidate(); } }
        public bool HorizontalEnabled { get => _horizontalEnabled; set { _horizontalEnabled = value; Invalidate(); } }
        public bool VerticalEnabled { get => _verticalEnabled; set { _verticalEnabled = value; Invalidate(); } }

        public tagPOINT Offset
        {
            get => _offset;
            set
            {
                _offset = value;
                Invalidate();
                Change?.Invoke(ID, _offset.x, _offset.y);
            }
        }

        public tagSIZE Increments { get => _increments; set => _increments = value; }

        public void CreateClient(ILayer pChild) { }

        public void ScrollTo(ref tagPOINT ptOffset)
        {
            _offset = ptOffset;
            Invalidate();
            Change?.Invoke(ID, _offset.x, _offset.y);
        }

        public void ResetScroller()
        {
            _offset = default;
            Invalidate();
        }

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