using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CommonFroms.G2D
{
    public class G2DRichTextBox : RichTextBox
    {
        public G2DRichTextBox()
        {
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys kd)
        {
            if (Focused)
            {
                if (Keyboard.IsCtrlDown)
                {
                    Keys keyData = kd ^ Keys.Control;
                    switch (keyData)
                    {
                        case Keys.C: DoCopy(); return true;
                        case Keys.V: if (!ReadOnly) DoPaste(); return true;
                        case Keys.X: if (!ReadOnly) DoCut(); return true;
                    }
                }
                else
                {
                    switch (kd)
                    {
                        case Keys.Delete: if (!ReadOnly) DoDelete(); return true;
                    }
                }
            }
            return base.ProcessCmdKey(ref msg, kd);
        }

        protected virtual void DoCopy()
        {
            if (this.SelectionLength > 0)
            {
                Clipboard.SetText(this.Text.Substring(this.SelectionStart, this.SelectionLength));
            }
        }
        protected virtual void DoPaste()
        {
            var text = this.Text;
            var clip = Clipboard.GetText();
            if (this.SelectionLength > 0)
            {
                text = text.Remove(this.SelectionStart, this.SelectionLength);
            }
            text = text.Insert(this.SelectionStart, clip);
            var new_pos = this.SelectionStart + clip.Length;
            this.Text = text;
            this.SelectionStart = new_pos;
            this.SelectionLength = 0;
        }
        protected virtual void DoDelete()
        {
            var text = this.Text;
            if (text.Length > 0)
            {
                if (this.SelectionLength > 0)
                {
                    text = text.Remove(this.SelectionStart, this.SelectionLength);
                }
                else if (this.SelectionStart < text.Length - 1)
                {
                    text = text.Substring(0, text.Length - 1);
                }
                this.Text = text;
            }
        }
        protected virtual void DoCut()
        {
            DoCopy();
            DoDelete();
        }
    }
}