using System;
using System.Collections.Generic;
using System.Linq;

using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.Plugins;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using BS.Shared.Services;

namespace DiakonieKKKleve.Validation
{
	public class DkkkServiceRecordValidator : ServiceRecordValidator
	{
		public override ServiceRecordValidationResultDC CheckOverlappingEmployeeServiceRecords(ServiceRecordDC newServiceRecord, DateTime start, long employeeOid, decimal roundedDuration)
		{
			bool isArbeitszeit = newServiceRecord.ServiceDescription.Category.Name == "Arbeitszeit";

			var span = new DateTimeSpan();
			span.StartDate = start.Date.AddDays(-1);
			span.EndDate = newServiceRecord.End.Value.Date.AddDays(1);
			IList<ServiceRecord> empRecords = DAOFactory.SearchDAO.FindEmployeeServiceRecords(employeeOid, span, null, null);
			if (newServiceRecord.ServiceRecordOid.HasValue)
			{
				empRecords = empRecords.Where(r => r.Oid != newServiceRecord.ServiceRecordOid.Value).ToList();
			}
			empRecords = empRecords.Where(r => r.Start.HasValue && r.Start.Value.Second == 0).ToList();

			if (isArbeitszeit)
			{
				empRecords = empRecords.Where(r => r.ServiceDescription.ServiceCategory.Name == "Arbeitszeit").ToList();
			}
			else
			{
				empRecords = empRecords.Where(r => r.ServiceDescription.ServiceCategory.Name != "Arbeitszeit").ToList();
			}
			try
			{
				ServiceRecord overlappingRecord =
					empRecords.FirstOrDefault(
						record =>
							TimeSpanOverlapsWithOtherTimeSpan(start, record.Start, roundedDuration, record.RoundedDuration));

				if (overlappingRecord != null)
				{
					var rdc = new ServiceRecordValidationResultDC
					{
						ResultType = ServiceRecordValidationResult.EmployeeOverlapping,
						Message = String.Format("{0}, Dauer {1:0} Minuten", overlappingRecord.Start.Value.ToShortTimeString(),
							overlappingRecord.GroupRoundedDuration ?? overlappingRecord.RoundedDuration)
					};

					Customer c = overlappingRecord.Customer;
					if (c != null)
					{
						rdc.Message += String.Format(" bei Klient/in {0}, {1}", c.Person.LastName, c.Person.FirstName);
					}
					Employee e = overlappingRecord.Employee;
					if (e != null)
					{
						rdc.EmployeeName = String.Format("{0} {1}", e.Person.FirstName, e.Person.LastName);
					}

					return rdc;
				}
			}
			catch (Exception)
			{
				return new ServiceRecordValidationResultDC { ResultType = ServiceRecordValidationResult.Error };
			}
			return null;
		}

		
	}
}