//
// Copyright (c) 2015, MindFusion LLC - Bulgaria.
//

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;


namespace MindFusion.Reporting.Wpf.Samples.CS.CustomReportItems
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			nwindDataSet dataSet = new nwindDataSet();
			nwindDataSetTableAdapters.CategoriesTableAdapter categoriesAdapter =
				new nwindDataSetTableAdapters.CategoriesTableAdapter();
			categoriesAdapter.Fill(dataSet.Categories);
			nwindDataSetTableAdapters.Sales_by_CategoryTableAdapter salesByCategoryAdapter =
				new nwindDataSetTableAdapters.Sales_by_CategoryTableAdapter();
			salesByCategoryAdapter.Fill(dataSet.Sales_by_Category);

			nwindDataSet.CategoriesDataTable categoryData = categoriesAdapter.GetData();
			nwindDataSet.Sales_by_CategoryDataTable salesByCategoryData = salesByCategoryAdapter.GetData();

			Report report = Report.FromDictionary(new Uri("CustomItemsReport.xaml", UriKind.Relative), "customItemsReport");
			report.DataContext = dataSet;
			report.QueryDetails += (s, e) =>
			{
				ReportItem item = s as ReportItem;
				if (item != null)
				{
					if (item.Name == "SalesRange")
					{
						nwindDataSet.CategoriesRow row = e.MasterRow as nwindDataSet.CategoriesRow;

						e.Details = salesByCategoryData.Where(
							sale => sale.CategoryID == row.CategoryID);
					}
					else if (item.Name == "myItem")
					{
						nwindDataSet.Sales_by_CategoryRow row = e.MasterRow as nwindDataSet.Sales_by_CategoryRow;

						nwindDataSet.CategoriesRow masterRow = categoryData.First(
							category => category.CategoryID == row.CategoryID);

						e.Details = salesByCategoryData.Where(
							sale => sale.CategoryID == masterRow.CategoryID);
					}
				}
			};
			report.Run();

			ReportLayout layout = report.Layout(new Size(8.5 * 96, 11 * 96),
				new Thickness(0.5 * 96), PageOrientation.Portrait);

			FixedDocumentRenderTarget renderTarget = new FixedDocumentRenderTarget();
			layout.RenderAllPages(renderTarget);

			viewer.Document = renderTarget.Document;
		}
	}
}
