using System;
using System.Collections.Generic;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.Invoicing;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BeWo.Data.Access;
using BeWo.Data.Entities;

namespace LHDuisburg.Invoicing
{
	public class LHDuisburgInvoiceFactory : InvoiceFactory
	{
		
		public override InvoiceCreation CreateInvoiceCreator(string specificId, string tenant, Dictionary<CompactSupportConceptDC, List<ServiceRecordDC>> supportConcepts2ServiceRecords)
		{
			foreach (var list in supportConcepts2ServiceRecords.Values)
			{
				
				foreach (var sr in list)
				{
					var sd = sr.ServiceDescription.Category;
					var ic = GetInvoiceCreatorForCategory(sd);
					if (ic != null)
						return ic;
				}
			}

			foreach (var item in supportConcepts2ServiceRecords)
			{
				var csc = item.Key;
				var sc = DAOFactory.GenericDAO.LoadByID<SupportConcept>(csc.SupportConceptOid);

				foreach (var sa in sc.ServiceAccountings)
				{
					if (sa.ServiceDescription != null && sa.ServiceDescription.ServiceCategory != null)
					{
						var scDc = MapperFactory.ServiceCategoryDC_ServiceCategory.MapToNewDC(sa.ServiceDescription.ServiceCategory);
						var ic = GetInvoiceCreatorForCategory(scDc);
						if (ic != null)
							return ic;
					}
				}
			}

			return new LHDuisburgHPFHInvoiceCreation();

				
		}

		private InvoiceCreation GetInvoiceCreatorForCategory(ServiceCategoryDC sd)
		{
			if (sd != null && !String.IsNullOrEmpty(sd.Name))
			{
				String cat = sd.Name.ToLower().Trim();
				if (cat.IndexOf("iff") >= 0)
				{
					return new LHDuisburgIFFInvoiceCreation();
				}
				else if (cat.IndexOf("direkte betreuungsleistung") >= 0)
				{
					return new LHDuisburgBeWoInvoiceCreation();
				}
				else if (cat.IndexOf("hpff") >= 0)
				{
					return new LHDuisburgFFInvoiceCreation();
				}
				else if (cat.IndexOf("hpfh") >= 0)
				{
					return new LHDuisburgHPFHInvoiceCreation();
				}
				else if (cat.StartsWith("eb"))
				{
					return new LHDuisburgEBInvoiceCreation();
				}
				else if (cat.StartsWith("stabi"))
				{
					return new LHDuisburgStabiFamInvoiceCreation();
				}
				else if (cat.StartsWith("tbt"))
				{
					return new LHDuisburgTBTInvoiceCreation();
				}
			}
			return null;
		}

	}
}
