using System;
using System.ServiceModel;

using Autofac;

using Autumn.Common;
using Autumn.Common.Sync;

using Common.Logging;

namespace Autumn.Server.Sync
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class SyncRouterService : ISyncRouterService
    {
        private readonly ILog _log;

        public SyncRouterService()
        {
            _log = IoC.Container.Resolve<ILog>();
        }

        public ISyncResponse Execute(ISyncRequest request)
        {
            try
            {
                _log.DebugFormat("Recieved sync request : {0}, Id - {1} @ {2}", request.GetType().Name, request.Id, DateTime.Now);

                var router = IoC.Container.Resolve<ISyncRouter>();

                var response = router.ExecuteRequest(request);

                _log.DebugFormat("Returning sync request : {0}, Id - {1} @ {2}", request.GetType().Name, request.Id, DateTime.Now);

                return response;
            }
            catch (Exception ex)
            {
                _log.DebugFormat("Failed sync request : {0}, Id - {1} @ {2}. {3}", request.GetType().Name, request.Id, DateTime.Now, ex.Message);

                var genericFault = new GenericFault
                                   {
                                       Operation = request.GetType().FullName,
                                       Message = ex.Message
                                   };

                throw new FaultException<GenericFault>(genericFault, ex.Message);
            }
        }
    }
}