using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms;
using EhLib;

namespace EhLib.Design
{
  public class MaskPropertyEditor : UITypeEditor
  {

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
      MaskedTextBoxEh maskedTextBoxEh = context.Instance as MaskedTextBoxEh;
      MaskedTextBox stdMasketTextBox;
      if (maskedTextBoxEh == null)
      {
        stdMasketTextBox = new MaskedTextBox();
        if (value is string)
          stdMasketTextBox.Mask = (string)value;
      }
      else
      {
        stdMasketTextBox = maskedTextBoxEh.TextBoxControl;
      }

      Type editorType = Type.GetType("System.Windows.Forms.Design.MaskPropertyEditor");
      UITypeEditor typeEditor = (UITypeEditor)Activator.CreateInstance(editorType);
      var stdMasketTextBoxContext = new EmbeddedMaskedTextBoxTypeDescriptorContext(context, stdMasketTextBox);
      return typeEditor.EditValue(stdMasketTextBoxContext, provider, value);
    }

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
      return UITypeEditorEditStyle.Modal;
    }

    public override bool GetPaintValueSupported(ITypeDescriptorContext context)
    {
      return false;
    }
  }

  internal class EmbeddedMaskedTextBoxTypeDescriptorContext : ITypeDescriptorContext
  {
    internal ITypeDescriptorContext extContext;
    internal MaskedTextBox stdMasketTextBox;

    public EmbeddedMaskedTextBoxTypeDescriptorContext(ITypeDescriptorContext context, MaskedTextBox stdMasketTextBox)
    {
      extContext = context;
      this.stdMasketTextBox = stdMasketTextBox;
    }

    public IContainer Container { get { return extContext.Container; } }

    public object Instance { get { return stdMasketTextBox; } }

    public PropertyDescriptor PropertyDescriptor { get { return extContext.PropertyDescriptor; } }

    public object GetService(Type serviceType)
    {
      return extContext.GetService(serviceType);
    }

    public void OnComponentChanged()
    {
      extContext.OnComponentChanged();
    }

    public bool OnComponentChanging()
    {
      return extContext.OnComponentChanging();
    }
  }
}
