using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace NotepadEnhanced.Refactexing
{
    public partial class RefactexPanel : UserControl
    {
        [Description("Occurs when the value of the Submittable property changes")]
        public event EventHandler SubmittableChanged = delegate {};

        public RefactexPanel()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Resets all controls to their original state
        /// </summary>
        public void ClearInput()
        {
            foreach (var textBox in this.Controls.OfType<TextBox>())
                textBox.Clear();

            regexOptionsPicker.UncheckAll();
        }

        /// <summary>
        /// Loads and displays the specified refactex
        /// </summary>
        public void LoadRefactex(Refactex refactex)
        {
            txtDescrip.Text = refactex.Description;
            txtName.Text = refactex.Name;
            regexOptionsPicker.Options = refactex.Options;
            txtPattern.Text = refactex.Pattern;
            txtReplacement.Text = refactex.Replacement;
        }

        private void MandatoryStringInput_TextChanged(object sender, EventArgs e)
        {
            Submittable = txtName.TextLength > 0 && txtPattern.TextLength > 0;
        }

        /// <summary>
        /// Gets or sets the currently displayed refactex
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Refactex Refactex
        {
            get
            {
                return new Refactex(txtName.Text, txtDescrip.Text, txtPattern.Text,
                    txtReplacement.Text, regexOptionsPicker.Options);
            }
            set
            {
                if (value == null) return;
                txtDescrip.Text = value.Description;
                txtName.Text = value.Name;
                regexOptionsPicker.Options = value.Options;
                txtPattern.Text = value.Pattern;
                txtReplacement.Text = value.Replacement;
            }
        }

        private bool _submittable;
        /// <summary>
        /// Gets whether there is enough info for this input to be submitted
        /// </summary>
        [Browsable(false)]
        public bool Submittable
        {
            get { return _submittable; }
            private set
            {
                bool changed = value != _submittable;

                if (changed)
                {
                    _submittable = value;
                    SubmittableChanged(this, EventArgs.Empty);
                }
            }
        }
    }
}
