using System;
using System.Linq;

using BeWo.Report;
using BeWo.Report.ReportObjects;

using DevExpress.XtraReports.UI;

namespace LWVEingliederungshilfe
{
    public partial class MonatsabrechnungABW : XtraReport, IBeWoReport<ServiceInvoiceRO>
    {
        public MonatsabrechnungABW()
        {
            InitializeComponent();
        }

        public void SetReportDataSource(ServiceInvoiceRO pRO)
        {
	        foreach (var item in pRO.ServiceInvoicePeriods.SelectMany(period => period.ServiceInvoiceItems))
	        {
		        item.GrossAmount = item.GrossAmount.Substring(0, item.GrossAmount.Length - 2);
	        }

	        var first = pRO.ServiceInvoicePeriods.FirstOrDefault(f => f.ServiceInvoiceItems.Any());

			if(first != null)
				StundensatzLabel.Text = string.Format("{0}", first.ServiceInvoiceItems.First().HourlyRateString);

	        var sumRoundedDuration = pRO.ServiceInvoicePeriods.Sum(period => period.ServiceInvoiceItems.Sum(item => item.ServiceRecord.RoundedDuration));
	        
	        SummeDirekteKontaktZeitLabel.Text = string.Format("{0}:{1:00}", (int)(sumRoundedDuration / 60), (int)sumRoundedDuration % 60);

	        var h = (int) sumRoundedDuration/60;
	        var m = (int) sumRoundedDuration%60;

	        decimal industrialTimeUnit = h + m/60m;
	        KontaktZeitIndustrieminutenLabel.Text = string.Format("{0:##.00}", industrialTimeUnit);

            bindingSource1.DataSource = pRO;
        }

		private void PersonRoundedDurationTableCell_EvaluateBinding(object sender, BindingEventArgs e)
		{
			var roundedDuration = Convert.ToDecimal(e.Value);

			e.Value = string.Format("{0}:{1:00}", (int) (roundedDuration/60), (int) roundedDuration%60);
		}

	    private void PersonCountTableCell_EvaluateBinding(object sender, BindingEventArgs e)
	    {
		    e.Value = e.Value ?? 1;
	    }

	    private void TotalRoundedDurationCell_EvaluateBinding(object sender, BindingEventArgs e)
		{
			var invoiceItem = GetCurrentServiceInvoiceItemRO((XRTableCell) sender);
			var roundedDuration = e.Value == null ? invoiceItem.ServiceRecord.RoundedDuration : Convert.ToDecimal(e.Value);

			e.Value = string.Format("{0}:{1:00}", (int)(roundedDuration / 60), (int)roundedDuration % 60);
		}

	    private static ServiceInvoiceItemRO GetCurrentServiceInvoiceItemRO(XRTableCell tableCell)
	    {
			var detailBand = (DetailBand)tableCell.Row.Table.Parent;
			return (ServiceInvoiceItemRO)detailBand.Report.GetCurrentRow();
	    }
    }
}