using Gebhardt.Shared;
using Gebhardt.Shared.Process.ProducerConsumer;
using Gebhardt.StoreWare.WcsWms.InterfaceWcsWms.Interfaces;
using System;
using Gebhardt.StoreWare.Wcs.HostBooking.InterfaceWcsWms.Interfaces;
using Unity;
using Gebhardt.StoreWare.Wcs.HostBooking.InterfaceWcsWms;

namespace Gebhardt.StoreWare.Wcs.HostBooking
{
	public class HostBookingConsumer : Consumer<IHostMessage>
	{
		private readonly IUnityContainer _unityContainer;

		public HostBookingConsumer(string name, int aliveTime, int queueLength, IUnityContainer unityContainer)
			: base(name, aliveTime, true, queueLength)
		{
			_unityContainer = unityContainer;
		}

		public override bool DoWork(IHostMessage hostMessage)
		{
			IHostMessageFromWmsService service = _unityContainer.Resolve<IHostMessageFromWmsService>();

			try
			{
				dynamic handler = _unityContainer.Resolve(typeof(IHandleRecord<>).MakeGenericType(hostMessage.GetType()), hostMessage.RecordType);
				Log.Write(LogLevel.Info, $"process message [{hostMessage}]");
				handler.Handle((dynamic)hostMessage);
				hostMessage.SetFinished();
			}
			catch (Exception e)
			{
				if (e.GetType() != typeof(FromWmsException))
				{
					Log.WriteException(e);
				}
				hostMessage.SetFailed(e.Message);
			}
			service.Update(hostMessage);
			return true;
		}
	}
}