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

namespace BeWo.Service.Invoicing
{

	internal class FedFahrtkostenInvoiceCreation : InvoiceCreation
	{
		private const decimal AMOUNT_PER_KM = 0.3m;

		private DateTime? accountingPeriodStart = null;
		private DateTime? accountingPeriodEnd = null;

		public override void SetInvoiceBaseData(int invoiceCounter, ServiceInvoice invoice, CostBearer costBearer, DateTimeSpan invoicePeriod,
			IList<CompactSupportConceptDC> supportConceptList)
		{
			if (invoicePeriod != null)
			{
				accountingPeriodStart = invoicePeriod.StartDate;
				accountingPeriodEnd = invoicePeriod.EndDate;
			}
			base.SetInvoiceBaseData(invoiceCounter, invoice, costBearer, invoicePeriod, supportConceptList);
		}

		public override void SetInvoiceId(ServiceInvoice invoice)
		{
			invoice.InvoiceBase.InvoiceId = "fed";
		}

		public override IList<InvoiceItem> CreateInvoiceItems(List<ServiceRecordDC> serviceRecordsInPeriod, DateTimeSpan invoicePeriod, SupportConceptApprovalPeriod scap, Calculations calc)
		{
			var list = base.CreateInvoiceItems(serviceRecordsInPeriod, invoicePeriod, scap, calc);

			InvoiceItem ttii = CreateFahrkostenInvoiceItem(serviceRecordsInPeriod, scap, calc);
			if (ttii != null)
				list.Add(ttii);
			return list;
		}

		private InvoiceItem CreateFahrkostenInvoiceItem(List<ServiceRecordDC> serviceRecordsInPeriod, SupportConceptApprovalPeriod scap, Calculations calc)
		{
			int anzahlFahrtkosten = 0;

			if (!accountingPeriodStart.HasValue)
				accountingPeriodStart = scap.StartDate;
			if (!accountingPeriodEnd.HasValue)
				accountingPeriodEnd = scap.EndDate;

			foreach (var sr in serviceRecordsInPeriod)
			{
				var sd = sr.ServiceDescription.Category;

				if (!String.IsNullOrEmpty(sd.Name) && sd.Name.ToLower() == "fed")
				{
					anzahlFahrtkosten++;
				}

			}

			var customer = scap.CostBearer2SupportConcept.SupportConcept.Customer;
			if (customer.DistanceInMeter.HasValue && customer.DistanceInMeter.Value > 0 && anzahlFahrtkosten > 0)
			{
				var invoiceItem = new InvoiceItem();
				invoiceItem.AmountPerUnit = AMOUNT_PER_KM*customer.DistanceInMeter.Value;
				invoiceItem.UnitCount = anzahlFahrtkosten;
				invoiceItem.AmountTotal = invoiceItem.UnitCount * invoiceItem.AmountPerUnit;
				invoiceItem.RateFactor = null;
				invoiceItem.ItemPeriodStart = accountingPeriodStart;
				invoiceItem.ItemPeriodEnd = accountingPeriodEnd;
				invoiceItem.GrossAmountTotal = invoiceItem.AmountTotal;
				invoiceItem.ItemDescription = String.Format("Fahrtkosten {0:0} x {1:0} km x {2:c}", anzahlFahrtkosten, customer.DistanceInMeter.Value, AMOUNT_PER_KM);
				if (scap != null)
					invoiceItem.SupportConceptApprovalPeriodOid = scap.Oid;



				return invoiceItem;
			}
			return null;
		}
	}
}
