//------------------------------------------------------------------------------
// <copyright file=”*.cs” company=”EhLib Team”>
//     Copyright (c) 2017 Dmitry V. Bolshakov   
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Diagnostics;

namespace EhLib.Design
{
  public class InEditControlEditor : ObjectSelectorEditor
  {
    protected override void FillTreeWithData(Selector selector,
            ITypeDescriptorContext context, IServiceProvider provider)
    {
      base.FillTreeWithData(selector, context, provider);

      selector.AddNode("(null)", null, null);

      ITypeDiscoveryService discoveryService = (ITypeDiscoveryService)context.GetService(typeof(ITypeDiscoveryService));
      ICollection inEditControlTypes = discoveryService.GetTypes(typeof(EditItem), false);

      foreach (Type t in inEditControlTypes)
      {
        if (t == typeof(EditItem))
          continue;

        if (t.IsAbstract)
          continue;

        if (!t.IsPublic && !t.IsNestedPublic)
          continue;

        selector.AddNode(t.ToString(), t, null);
      }

      selector.ShowLines = true;
      selector.ExpandAll();
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
      object result = base.EditValue(context, provider, value);
      if ((result != prevValue) && ((result is Type) || (result == null)))
      {
        //InEditControl inEditControl = null;
        if ((prevValue != null) && (prevValue is IComponent))
          ((IComponent)prevValue).Dispose();
        Type resultType = (Type)result;
        if (result != null)
        {
          Debug.Assert(context != null, @"context != null");
          IDesignerHost host = (IDesignerHost)context.GetService(typeof(IDesignerHost));
          result = (EditItem)host.CreateComponent(resultType);
        }
      }
      return result;
    }

    public override void SetValue(object value)
    {
      //InEditControl inEditControl = null;
      //if (value is Type)
      //{
      //  Type result = (Type)value;
      //  if (result != null)
      //  {
      //    IDesignerHost host = (IDesignerHost)context.GetService(typeof(IDesignerHost));
      //    inEditControl = (InEditControl)host.CreateComponent(typeof(InEditControl));
      //  }
      //}
      //else
        base.SetValue(value);
    }

  }

  public class InEditControlDesigner : ComponentDesigner
  {

    //TextBoxEh editControl
    public EditItem InEditControl
    {
      get
      {
        return (EditItem)Component;
      }
    }

    protected override IComponent ParentComponent
    {
      get
      {
        if (InEditControl != null)
          return InEditControl.EditControl;
        else
          return null;
      }
    }

  }
}