using System;
using System.Collections;
using System.Collections.Generic;
using _1_Model;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Query;

namespace _5A_WCFService
{
  public class Service1 : IService1, IDisposable
  {

    public List<Category> GetCategories()
    {
      IObjectScope scope = NorthwindProvider.GetNewObjectScope();
      scope.Transaction.Begin(); 

      var queryable =
        from category
          in scope.Extent<Category>()
        select category;

      List<Category> cat = queryable.ToList();

      scope.Transaction.Rollback();
      scope.Dispose(); 

      return cat; 
    }

    public List<Product> GetProducts(int categoryID)
    {
      IObjectScope scope = NorthwindProvider.ObjectScope();

      var queryable =
        from product
          in scope.Extent<Product>()
        where product.CategoryID == categoryID
        select product;
      return queryable.ToList();
    }

    public ObjectContainer.ChangeSet GetProductsByCategory(int categoryID)
    {
      IObjectScope scope = NorthwindProvider.GetNewObjectScope();

      scope.Transaction.Begin();

      IEnumerable products = from product in scope.Extent<Product>()
                             where product.CategoryID == categoryID
                             select product;

      ObjectContainer container = new ObjectContainer();

      IObjectCollector collector =
        new FetchGroupCollector(FetchGroupCollector.DefaultFetchGroup);

      // copy the products to the container and name the "Named List" by category
      container.CopyFrom(scope, categoryID.ToString(), products, collector);

      // get everything in the container as a changeset
      ObjectContainer.ChangeSet changeSet = container.GetContent();

      // we only need the changeSet and can Rollback the transaction
      scope.Transaction.Rollback();

      scope.Dispose(); 

      return changeSet;
    }

    public ObjectContainer.ChangeSet 
      UpdateProducts(ObjectContainer.ChangeSet changeSet)
    {
      IObjectScope scope = NorthwindProvider.ObjectScope();
      
      // commit the changeset from the client 
      return ObjectContainer.CommitChanges(changeSet,
          ObjectContainer.Verify.All, scope, true, true);
    }

    #region IDisposable Members

    public void Dispose()
    {
      NorthwindProvider.ObjectScope().Dispose();
    }

    #endregion

  }
}
