using System;
using System.Collections.Generic;
using System.Linq;
using BeWo.Data.Entities;
using BeWo.Service.Invoicing;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Services;

namespace BeWo.Club74
{
	public class Club74InvoiceCreation : InvoiceCreation
	{
		public override void SetServiceInvoicePeriods(ServiceInvoice invoice, CostBearer2SupportConcept costBearer2SupportConcept,
			DateTimeSpan invoicePeriod, List<ServiceRecordDC> serviceRecords)
		{
			base.SetServiceInvoicePeriods(invoice, costBearer2SupportConcept, invoicePeriod, serviceRecords);

			if (invoice.ServiceInvoicePeriodList.Count > 1)
			{
				if (invoice.ServiceInvoicePeriodList.All(s => s.SupportConceptApprovalPeriod.ServiceCategory == null))
				{
					var allItems = new List<InvoiceItem>();
					foreach (var sip in invoice.ServiceInvoicePeriodList)
					{
						allItems.AddRange(sip.InvoiceItemList);
					}

					var summary = base.CreateSummaryInvoiceItems(allItems, invoicePeriod,
						costBearer2SupportConcept.ApprovalPeriodList[0], null);

					var newPeriodList = new List<ServiceInvoicePeriod>();
					newPeriodList.Add(invoice.ServiceInvoicePeriodList[0]);
					invoice.ServiceInvoicePeriodList[0].InvoiceItemList = summary;

					invoice.ServiceInvoicePeriodList = newPeriodList;
				}
				else
				{
					foreach (var sip in invoice.ServiceInvoicePeriodList)
					{
						sip.InvoiceItemList = base.CreateSummaryInvoiceItems(sip.InvoiceItemList, invoicePeriod, costBearer2SupportConcept.ApprovalPeriodList[0], null);
					}
				}
			}
			else if (invoice.ServiceInvoicePeriodList.Count > 0)
			{
				invoice.ServiceInvoicePeriodList[0].InvoiceItemList = base.CreateSummaryInvoiceItems(invoice.ServiceInvoicePeriodList[0].InvoiceItemList, invoicePeriod, costBearer2SupportConcept.ApprovalPeriodList[0], null);
			}

		}

		public override InvoiceItem CreateInvoiceItem(ServiceRecordDC iServiceRecord, SupportConceptApprovalPeriod scap, Calculations calc)
		{
			var ii = base.CreateInvoiceItem(iServiceRecord, scap, calc);
			ii.ItemDescription = "Ambulant Betreutes Wohnen";

			return ii;
		}

		public override IList<InvoiceItem> CreateSummaryInvoiceItems(IList<InvoiceItem> itemList, DateTimeSpan invoicePeriod, SupportConceptApprovalPeriod scap,
			Calculations calc)
		{
			return itemList;
		}
	}
}
