using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Report.ReportObjects;
using BeWo.Report;
using BeWo.Service.ServiceImplementations;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using DevExpress.XtraReports.UI;
using System.Data;

namespace BeWo.GpzBiberachReports 
{
	public partial class KlientenListe : DevExpress.XtraReports.UI.XtraReport, IBeWoReport<QueryRO>
    {
		public KlientenListe()
        {
            InitializeComponent();

        }

        public void SetReportDataSource(QueryRO pRO)
        {
			this.bindingSource1.DataSource = CreateTable(pRO); ;
        }

		private QueryRO CreateTable(QueryRO ro)
		{
			OperationsServiceImp opService = new OperationsServiceImp();

		    QueryRO newQueryRo = new QueryRO();
		    int year = 0;
		    String categoryName = "";
		    if (ro.Rows != null)
		    {
			    DateTime dt;
			    if (DateTime.TryParse(ro.Rows[0].Field1.ToString(), out dt))
			    {
				    year = dt.Year;

				    
			    }
				lblHeader.Text = String.Format("{0} {1:yyyy}", ro.Rows[0].Field2, dt);
			    categoryName = ro.Rows[0].Field3 as String;

				//if (ro.Rows[0].Field4 != null && ro.Rows[0].Field4 == "1")
				//{
				//	showHours = true;
				//}
		    }
			Dictionary<long, VarFieldDef> oid2VarfieldDef = new Dictionary<long, VarFieldDef>();
			var varFieldDefs = DAOFactory.GenericDAO.GetAllActive<VarFieldDef>();
			foreach (var varFieldDef in varFieldDefs)
			{
				oid2VarfieldDef.Add(varFieldDef.Oid.Value, varFieldDef);
			}
			IList<SupportConcept> list = DAOFactory.GenericDAO.GetAllActiveAndArchived<SupportConcept>();

		    Dictionary<long, bool> c2sOids = new Dictionary<long, bool>();

		    foreach (SupportConcept sc in list)
		    {
			    if (sc.CostBearer2SupportConceptList != null && sc.CostBearer2SupportConceptList.Count > 0)
			    {
				    foreach (CostBearer2SupportConcept cb2sc in sc.CostBearer2SupportConceptList)
				    {
					    if (!c2sOids.ContainsKey(cb2sc.Oid.Value))
					    {
							SupportConceptStatisticsDC stats = null; 

						    foreach (var scap in cb2sc.ApprovalPeriodList)
						    {
								if (scap.ServiceCategory != null && scap.ServiceCategory.Name.ToLower().StartsWith(categoryName)
							        && scap.StartDate.HasValue
							        && (scap.StartDate.Value.Year <= year && (!scap.EndDate.HasValue || scap.EndDate.Value.Year >= year)))
							    {

								    if (stats == null)
								    {
										stats = opService.CreateSupportConceptStatistics(cb2sc.Oid.Value, DateTime.Now);
								    }
								    QueryRO.Row row = new QueryRO.Row();

								    DateTime start = scap.StartDate.Value;
								    DateTime? end = scap.EndDate;

								    StringBuilder sb = new StringBuilder();

								    sb.Append(start.ToShortDateString());
								    sb.Append(" - ");

								    if (end != null)
								    {
									    sb.Append(end.Value.ToShortDateString());
								    }

								    //Klient
								    row.Field1 = String.Format("{0}, {1}", sc.Customer.Person.LastName,
									    sc.Customer.Person.FirstName);
								    //HP Zeitraum
								    row.Field2 = String.Format("{0}", sb);

								    //Kostenträger
								    if (cb2sc.CostBearer.Organisation != null)
									    row.Field3 = String.Format("{0}", cb2sc.CostBearer.Organisation.Name);
								    //Geburtstag
								    row.Field4 = String.Format("{0:dd.MM.yyyy}", sc.Customer.Person.DateOfBirth);
								    //Geschlecht
								    if (sc.Customer.Person.Sex.HasValue)
									    row.Field5 = String.Format("{0:dd.MM.yyyy}",
										    sc.Customer.Person.Sex.Value == Sex.Male ? "männlich" : "weiblich");

								    //Adresse
								    if (sc.Customer.Person.Address != null)
								    {
									    row.Field6 = String.Format("{0}", sc.Customer.Person.Address.Street);
									    row.Field7 = String.Format("{0}", sc.Customer.Person.Address.PostalCode);
									    row.Field8 = String.Format("{0}", sc.Customer.Person.Address.Town);
								    }

								    //Nationalität
								    row.Field9 = String.Format("{0}", GetVarFieldValue(sc.Customer, oid2VarfieldDef, "Nationalität"));
									var mh = GetVarFieldValue(sc.Customer, oid2VarfieldDef, "Migrationshintergrund");
									if (!String.IsNullOrEmpty(mh) && mh == "True")
									{
										row.Field10 = String.Format("{0}", "Ja");
									}
 
										
									row.Field11 = String.Format("{0:0.00}", stats.MinutesApprovedTotal / 60);
									row.Field12 = String.Format("{0:0.00}", stats.MinutesProvidedTotalRounded / 60);

									String mainAttendant = "";
									foreach (Employee2Customer e2c in sc.Customer.Employee2CustomerList)
									{
										foreach (ValueListEntry2Object vle2o in e2c.ValueList)
										{
											ValueListEntry vle = vle2o.Entry;
											if (vle.SystemEntryID != null && vle.SystemEntryID.Value == SystemEntryID.EmployeeRoleMainAttendant)
											{
												string empName = e2c.Employee.Person.FirstName + " " + e2c.Employee.Person.LastName;
												if (String.IsNullOrEmpty(mainAttendant))
													mainAttendant = empName;
												else
												{
													if (!mainAttendant.Contains(empName))
													{
														mainAttendant += ", " + empName;
													}
												}
											}
										}
									}
								    row.Field13 = mainAttendant;
								    newQueryRo.Rows.Add(row);
							    }
						    }
					    }
				    }
			    }
		    }


		    newQueryRo.Rows.Sort((a, b) => a.Field1.ToString().CompareTo(b.Field1));

		    return newQueryRo;
	    }

		private String GetVarFieldValue(Customer customer, Dictionary<long, VarFieldDef> oid2VarfieldDef, string varFieldName)
		{
			
			if (customer.VarFieldValueList != null)
			{
				foreach (var varField in customer.VarFieldValueList)
				{
					if (oid2VarfieldDef.ContainsKey(varField.VarFieldDefOid.Value))
					{
						var def = oid2VarfieldDef[varField.VarFieldDefOid.Value];

						if (def.Label == varFieldName)
						{
							var varFieldValue = Utils.XMLDeserializeFromString(varField.SerializedValue, Type.GetType(varField.TypeName));
							if (varFieldValue != null)
							{
								return varFieldValue.ToString();
								
							}
							
						}
					}
				}
			}
			return String.Empty;
		}
    }
}
