using RodionovLibrary.Exceptions;
using System.Text.RegularExpressions;


namespace RodionovLibrary.VisualComponents
{
    public partial class TextBoxControl : UserControl
    {
        private string? tooltipText;

        private event EventHandler? _valueChanged;

        public event EventHandler ValueChanged
        {
            add { _valueChanged += value; }
            remove { _valueChanged -= value; }
        }

        public string? Pattern { get; set; }

        public string Value { 
            get 
            {
                if (string.IsNullOrEmpty(Pattern))
                    throw new NullPatternException("Не задан шаблон");
                if (!new Regex(Pattern).IsMatch(textBox.Text))
                    throw new NotMatchPatternException("Введенное значение не соответствует шаблону");
                return textBox.Text;
            } 
            set 
            {
                if (!string.IsNullOrEmpty(Pattern) && new Regex(Pattern).IsMatch(value))
                    textBox.Text = value;
            } 
        }

        public TextBoxControl()
        {
            InitializeComponent();
        }

        public void SetTooltipText(string text)
        {
            tooltipText = text;
        }

        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            _valueChanged?.Invoke(sender, e);
        }

        private void TextBox_MouseEnter(object sender, EventArgs e)
        {
            toolTip.Show(tooltipText ?? "", textBox, 45, 20, 3000);
        }
    }
}