using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace NotepadEnhanced.GUI.Controls
{
    public class HotTrackedTextBox : TextBox
    {
        private Graphics _graphics;
        private bool _isPaintRegistered;
        private const int _STROKE_SIZE = 1;

        private void Parent_Paint(object sender, PaintEventArgs e)
        {
            base.OnPaint(e);

            if (this.ContainsFocus)
            {
                DrawHotTrack(Brushes.Goldenrod);
            }
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);

            if (!this.ContainsFocus) DrawHotTrack(Brushes.CornflowerBlue);
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);

            if (!this.ContainsFocus) ClearHotTrack();
        }

        protected override void OnEnter(EventArgs e)
        {
            base.OnEnter(e);
            DrawHotTrack(Brushes.Goldenrod);
        }

        protected override void OnParentChanged(EventArgs e)
        {
            base.OnParentChanged(e);

            if (_graphics == null)
            {
                _graphics = this.Parent.CreateGraphics();
            }

            if (!_isPaintRegistered)
            {
                this.Parent.Paint += Parent_Paint;
                _isPaintRegistered = true;
            }
        }

        protected override void OnLeave(EventArgs e)
        {
            base.OnLeave(e);
            ClearHotTrack();
        }

        private void ClearHotTrack()
        {
            Brush brush = new SolidBrush(this.Parent.BackColor);
            DrawHotTrack(brush);
        }

        private void DrawHotTrack(Brush brush)
        {
            if (_graphics != null)
            {
                 _graphics.CompositingQuality = CompositingQuality.HighQuality;
                 _graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 _graphics.SmoothingMode = SmoothingMode.AntiAlias;

                int xPos = this.Location.X - _STROKE_SIZE;
                int yPos = this.Location.Y - _STROKE_SIZE;
                int width = this.Size.Width + _STROKE_SIZE * 2;
                int height = this.Size.Height + _STROKE_SIZE * 2;
                _graphics.FillRectangle(brush, xPos, yPos, width, height);
            }
        }
    }
}
