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

namespace WinFormClient
{
    public class ContainerHelper
    {
        private ObjectContainer _container = new ObjectContainer();

        public IList<T> Load<T>(ObjectContainer.ChangeSet changeSet)
        {
            // ChangeSet contstructor morphs 
            // webservice changeset to application changeset type
            ObjectContainer.ChangeSet tempChangeSet =
              new ObjectContainer.ChangeSet(changeSet);

            // transaction must not be active before call to Apply()
            if (_container.Transaction.IsActive)
                _container.Transaction.Commit();

            // apply service changeset to local container
            // transaction must not be active
            _container.Apply(tempChangeSet);

            // start transaction for new add/edit/delete in the bound controls
            _container.Transaction.Begin();

            return _container.Extent<T>();
        }

        public delegate ObjectContainer.ChangeSet
          SynchronizeDelegate(ObjectContainer.ChangeSet changeSet);

        public void Save(SynchronizeDelegate synchronize)
        {
            // transactions cannot be active for GetChanges() or Apply()
            if (_container.Transaction.IsActive)
                _container.Transaction.Commit();

            // get the changes from the client
            ObjectContainer.ChangeSet localChangeSet =
              _container.GetChanges(ObjectContainer.Verify.Changed);

            // send changes to the service, apply and return new
            // changeset
            ObjectContainer.ChangeSet serviceChangeSet =
              synchronize(localChangeSet);

            // apply synchronized changeset
            if (serviceChangeSet != null)
                _container.Apply(serviceChangeSet);

            // start transaction for new add/edit/delete in the bound controls
            _container.Transaction.Begin();
        }

        public void Add(object obj)
        {
            _container.Add(obj);
        }

        public void Remove(object obj)
        {
            _container.Remove(obj);
        }
    }
}
