using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using BeWo.Data.Entities;
using BS.Shared.Core;
using DevExpress.XtraReports.UI;
using BeWo.Report.ReportObjects;
using BeWo.Report;
using System.Collections.Generic;
using BS.Shared;

namespace BeWo.LebenshilfeDuisburgReports
{
	public partial class QuittierungsbelegFF : DevExpress.XtraReports.UI.XtraReport, IBeWoReport<ServicesOverviewRO>
    {
		public QuittierungsbelegFF()
        {
            InitializeComponent();
        }

        public void SetReportDataSource(ServicesOverviewRO pRO)
        {
			if (pRO.Services != null)
			{
				foreach (ServicesOverviewRO.ServiceDetail s in pRO.Services)
				{
					String sd = s.ServiceDescription;

					if (!String.IsNullOrEmpty(sd) && sd.StartsWith("Nachholtermin"))
					{
						String firstLine = "";
						if (!String.IsNullOrEmpty(s.Notice))
						{
							if (s.Notice.IndexOf(Environment.NewLine) >= 0)
								firstLine = s.Notice.Substring(0, s.Notice.IndexOf(Environment.NewLine));
							else
								firstLine = s.Notice;
						}

						s.ServiceDescription = String.Format("{0} vom {1}", sd, firstLine);
					}
				}

			}
			StringBuilder sb = new StringBuilder();
	        var org = GetOrganisation(pRO);
	        if (org != null)
	        {
				if (org.Name.StartsWith("Amt für Soziales"))
					sb.AppendLine("Stadt Duisburg");
		        sb.AppendLine(org.Name);
		        if (org.Address != null)
		        {
			        sb.AppendLine(org.Address.Street);
					sb.Append(org.Address.PostalCode);
			        sb.Append(" ");
					sb.Append(org.Address.Town);
		        }

	        }
			lblAddress.Text = sb.ToString();

			
            this.bindingSource1.DataSource = pRO;
        }

		private Organisation GetOrganisation(ServicesOverviewRO pRO)
		{
			if (pRO.CostBearer2SupportConceptList != null && pRO.CostBearer2SupportConceptList.Count > 0)
			{
				var kk = GetKrankenkasse(pRO);
				if (kk == null || pRO.CostBearer2SupportConceptList.Count == 0)
				{

					return pRO.CostBearer2SupportConceptList[0].CostBearer.Organisation;
				}
				else
				{
					foreach (var c2s in pRO.CostBearer2SupportConceptList)
					{
						if (c2s.CostBearer.Organisation != null && c2s.CostBearer.Organisation.Name != kk.Organisation.Name)
						{
							return c2s.CostBearer.Organisation;
						}
					}
				}
			}

			return null;
		}

		private Customer2Organisation GetKrankenkasse(ServicesOverviewRO pRO)
		{
			if (pRO.CostBearer2SupportConceptList != null && pRO.CostBearer2SupportConceptList.Count > 0)
			{
				var customer = pRO.CostBearer2SupportConceptList[0].SupportConcept.Customer;

				foreach (var c2o in customer.Customer2OrganisationList)
				{
					foreach (var v2e in c2o.ValueList)
					{
						if (v2e.Entry.Type == ValueListEntryType.EnvironmentOrganisationType && v2e.Entry.Value == "Krankenkasse")
						{
							return c2o;
						}
					}

				}

			}

			return null;
		}
    }
}
