using System;
using System.ComponentModel;
using System.ComponentModel.Design;


namespace DPLib
{
    /// <summary>
    /// A custom collection editor for ScriptCollection to provide naming and 
    /// id as required by the ClientScripts control.
    /// </summary>
    public class ScriptCollectionEditor : CollectionEditor
    {
        public ScriptCollectionEditor(Type type) : base(type)
        {
        }

        protected override object CreateInstance(Type itemType)
        {
            // Create the script instance.
            ClientScript script = (ClientScript)Activator.CreateInstance(typeof(ClientScript));

            if ( this.Context.Instance!=null)
            {
                string newBaseName = "clientScript";

                // Get the collection instance being edited.
                ClientScripts cs = (ClientScripts)this.Context.Instance;
                ScriptCollection csc = cs.Scripts;

                int count = csc.Count + 1;
                string newID = string.Empty;

                do
                {
                    // Set the script.ID to an appropriate name for displaying in 
                    // the control and collection editor.
                    newID = newBaseName + count.ToString();
                    count++;

                } while (csc.Contains(newID));
                script.ID = newID;
            }

            return script;
        }

    }


    ///<summary>
    /// A custom TypeConverter is required to display the scriptID in the 
    /// Members window of the custom collection editor.
    /// </summary>
    public class ClientScriptTypeConverter : TypeConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, 
            System.Globalization.CultureInfo culture, 
            object value, 
            Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                ClientScript script = (ClientScript)value;
                return script.ID;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}