using System;
using System.Collections;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections.Generic;

using FactorsNamespace;

namespace ProtoReports
{
	class CFilter
	{
		private String val;
		public void SetFilter(String filter)
		{
			val = filter;
		}
	}

	class mDataProvider
	{
		private fkarelDataSet.X_M506DataTable originalDBTable;
		private DataTable beforeCalculatingTable;
		private DataTable afterCalculatingTable;

		private fkarelDataSetTableAdapters.X_M506TableAdapter adapterForOriginalTable;
		private CFilter filter;//is Filter array better ?

		internal CFilter Filter
		{
			get { return filter; }
			set { filter = value; }
		}



		public mDataProvider()
		{
			originalDBTable = new fkarelDataSet.X_M506DataTable();
			adapterForOriginalTable = new ProtoReports.fkarelDataSetTableAdapters.X_M506TableAdapter();
			adapterForOriginalTable.Fill(originalDBTable);

//			sortedFactors = new FutureFactor[0];
			//!! todo: loading dll
			Assembly a = Assembly.LoadFrom("my.dll");
			Type CCalculator = a.GetType("ColumnCalculator.Calculator");
			Object factorsCalculator = CCalculator.InvokeMember(CCalculator.Name,
				BindingFlags.CreateInstance, null, null, new object[0]);

			FieldInfo factorsField = CCalculator.GetField("factorsList");
			sortedFactors = (List<FutureFactor>)factorsField.GetValue(factorsCalculator);

		}

		private List<FutureFactor> sortedFactors;

		public DataTable Select()
		{
			//
//			foreach (DataRow row in originalDBTable.Rows)
			afterCalculatingTable = beforeCalculatingTable.Copy();

			foreach (FutureFactor f in sortedFactors)
			{
				if (!(f is FutureDBFactor))
				{
					afterCalculatingTable.Columns.Add(f.Name);
				}
			}

			DataRow row;
			for (int i = 0; i < afterCalculatingTable.Rows.Count; i++)
			{
				row = afterCalculatingTable.Rows[i];
				foreach (FutureFactor f in sortedFactors)
				{
					f.GetValue(row);
				}
			}
			return afterCalculatingTable;
		}

		public DataTable SelectOriginal()//FutureDBFactor [] DBFactors)
		{
			//!! todo: как это правильно надо делать?
			ArrayList templist = new ArrayList();
			foreach (FutureFactor f in sortedFactors)
			{
				if (f is FutureDBFactor)
				{
					templist.Add(f);
				}
			}
			FutureDBFactor[] DBFactors = new FutureDBFactor[templist.Count];
			templist.CopyTo(DBFactors);


#region //!! todo: сдесь надо делать нормальный селект с правильным отображением столбцов.
			// а пока прост понаглому копируем только правильные колонки
			DataTable resTable = new DataTable();
			DataRow[] tempRows = originalDBTable.Select(filter + "");

			foreach (FutureDBFactor f in DBFactors)
			{
				resTable.Columns.Add(f.Name);
			}

			foreach(DataRow sourceRow in tempRows)
			{
				DataRow r = resTable.Rows.Add();
				foreach (FutureDBFactor f in DBFactors)
				{
					r[f.Name] = sourceRow[f.DBName];
				}
			}
#endregion			//

			return beforeCalculatingTable = resTable;
		}
	}
}
