using System.Linq;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Query;

namespace DataAccess
{
  public class ContainerManager
  {
    // return a ChangeSet loaded with objects populated from the database
    public static ObjectContainer.ChangeSet LoadChangeSet<T>()
    {
      ObjectContainer.ChangeSet changeSet = null;

      // get a new object scope for data access in this method
      using (IObjectScope scope = DataAccessScopeProvider.GetNewObjectScope())
      {
        // extract data for <T> and place in an IQueryable
        IQueryable<T> queryable =
            from q
              in scope.Extent<T>()
            select q;

        // create a container to hold the data
        ObjectContainer container = new ObjectContainer();

        // define the FetchGroup as default for the copy (fetches all fields)
        IObjectCollector collector =
          new FetchGroupCollector(FetchGroupCollector.DefaultFetchGroup);

        // copy everything from the IQueryable, and name the list as the 
        // <T> type name
        container.CopyFrom(scope, typeof(T).Name, queryable, collector);

        // save the current container content in a ChangeSet
        changeSet = container.GetContent();
      }

      return changeSet;
    }

    public static ObjectContainer.ChangeSet SaveChangeSet(
      ObjectContainer.ChangeSet changeSet)
    {
      ObjectContainer.ChangeSet result = null;

      using (IObjectScope scope = DataAccessScopeProvider.GetNewObjectScope())
      {
        // commit the changeset from the client and return the updated set 
        result = ObjectContainer.CommitChanges(changeSet,
              ObjectContainer.Verify.All, scope, true, true);
      }
      return result;
    }

    public static IQueryable<T> LoadQueryable<T>(
      ObjectContainer.ChangeSet changeSet)
    {
      ObjectContainer container = new ObjectContainer();
      container.Apply(changeSet);
      return container.Extent<T>().AsQueryable<T>();
    }

  }

}
