using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.Design;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using Csla;
using Csla.Web.Design;
namespace Csla.Web.Design
{
  /// 
  /// Object providing schema information for a
  /// business object.
  /// 
  [Serializable()]
  public class ObjectViewSchema : IDataSourceViewSchema
  {
    private string _typeName = "";
    private CslaDataSourceDesigner _designer;
    /// 
    /// Create an instance of the object.
    /// 
    /// Site containing the control.
    /// The business class for
    /// which to generate the schema.
    public ObjectViewSchema(CslaDataSourceDesigner site, string typeName)
    {
      _typeName = typeName;
      _designer = site;
    }
    /// 
    /// Returns a list of child schemas belonging to the
    /// object.
    /// 
    /// This schema object only returns
    /// schema for the object itself, so GetChildren will
    /// always return Nothing (null in C#).
    public System.Web.UI.Design.IDataSourceViewSchema[] GetChildren()
    {
      return null;
    }
    /// 
    /// Returns schema information for each property on
    /// the object.
    /// 
    /// All public properties on the object
    /// will be reflected in this schema list except
    /// for those properties where the 
    /// Browsable attribute
    /// is False.
    /// 
    public System.Web.UI.Design.IDataSourceFieldSchema[] GetFields()
    {
      ITypeResolutionService typeService = null;
      List result = new List();
      if (_designer != null)
      {
        Type objectType = null;
        try
        {
          typeService = (ITypeResolutionService)(_designer.Site.GetService(typeof(ITypeResolutionService)));
          objectType = typeService.GetType(_typeName, true, false);
          if (typeof(IEnumerable).IsAssignableFrom(objectType))
          {
            // this is a list so get the item type
            objectType = Utilities.GetChildItemType(objectType);
          }
          PropertyDescriptorCollection props = TypeDescriptor.GetProperties(objectType);
          foreach (PropertyDescriptor item in props)
          {
            if (item.IsBrowsable)
            {
              result.Add(new ObjectFieldInfo(item));
            }
          }
        }
        catch
        { /* do nothing - just swallow exception */ }
      }
      return result.ToArray();
    }
    /// 
    /// Returns the name of the schema.
    /// 
    public string Name
    {
      get
      {
        return "Default";
      }
    }
  }
}