using Model;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Query;

namespace Service
{
  public class Service1 : IService1
  {
    private static ObjectContainer.ChangeSet GetChangeSet(string listName,
      IObjectScope scope, object queryable)
    {
      ObjectContainer container = new ObjectContainer();

      // define the fetch groups used in the copy, by default all columns
      IObjectCollector collector =
        new FetchGroupCollector(FetchGroupCollector.DefaultFetchGroup);

      container.CopyFrom(scope, queryable.GetType().Name, queryable, collector);

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

      return changeSet;
    }

    public ObjectContainer.ChangeSet GetContactGroups()
    {
      ObjectContainer.ChangeSet changeSet = null;
      using (IObjectScope scope = ServiceScopeProvider.GetNewObjectScope())
      {
        var queryable =
            from q
              in scope.Extent<ContactGroup>()
            select q;

        changeSet = GetChangeSet("ContactGroups", scope, queryable);
      }
      return changeSet;
    }

    public ObjectContainer.ChangeSet GetContacts()
    {
      ObjectContainer.ChangeSet changeSet = null;
      using (IObjectScope scope = ServiceScopeProvider.GetNewObjectScope())
      {
        var queryable =
         from q
           in scope.Extent<Contact>()
         select q;

        changeSet = GetChangeSet("Contacts", scope, queryable);

      }
      return changeSet;
    }

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

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


  }
}
