using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using QC.CTDS.DM.DataStructures;
using QC.CTDS.DM.DataStructures.FormatDescriptorStructure;
using QC.CTDS.DM.DataStructures.InputDataStructure;
using QC.CTDS.DM.DataStructures.LimitDescriptorDataStructure;
using QC.CTDS.DM.DataStructures.OutputDataStructure;
using QC.CTDS.DM.SharedLibrary;

namespace QC.CTDS.DM.DataProcessor;

internal class WideSummaryProcessor : IDescriptorProcessor
{
	private const string EMPTY_DISCRIMINATOR = "EMPTY_DISC";

	private const string GROUPNAME_DISCRIMINATOR = "GROUP_NAME";

	private const string CUSTOM_LIMITS = "limits:";

	private WideCondensedSummary fdWideSummaryDescriptor;

	internal ReportSettings reportSettings;

	internal List<TestRunInfo> testRuns;

	public OutputGroup ProcessDescriptorData(ReportSettings reportSettings, GroupSetDescriptor groupSetDesc, List<TestRunInfo> testRuns)
	{
		this.reportSettings = reportSettings;
		fdWideSummaryDescriptor = groupSetDesc as WideCondensedSummary;
		this.testRuns = testRuns;
		if (fdWideSummaryDescriptor == null)
		{
			throw new Exception("Unsupported descriptor type");
		}
		OutputGroup outputGroup = new OutputGroup();
		outputGroup.Name = fdWideSummaryDescriptor.Name;
		testRuns = DataProcessorUtils.GetTestFilteredSourceData(fdWideSummaryDescriptor.StatisticsResultsBin.StatsResult.Where((StatisticsResultDataSet res) => !string.IsNullOrEmpty(res.testID) && !string.IsNullOrEmpty(res.resID)), testRuns);
		if (testRuns.Count > 0)
		{
			List<DiscGroup> chartGroupedItems = DataProcessorUtils.GetFilteredSourceData(fdWideSummaryDescriptor, testRuns, fdWideSummaryDescriptor.sort);
			string globalColName = string.Join(":", fdWideSummaryDescriptor.GetDistinctDiscriminatorIDOrNames().ToArray());
			if (chartGroupedItems.Count <= 0)
			{
				return outputGroup;
			}
			WideSummaryData[] wideSummaryDataArray = new WideSummaryData[chartGroupedItems.Count];
			CommonFunctions.RunLoop(reportSettings.RunInSequentialMode, 0, chartGroupedItems.Count, delegate(int index)
			{
				wideSummaryDataArray[index] = ProcessBinData(fdWideSummaryDescriptor.StatisticsResultsBin, chartGroupedItems[index].TestItems, chartGroupedItems[index].ParamsDict, globalColName, chartGroupedItems[index].ParamVisiblityInfo);
			});
			for (int i = 0; i < wideSummaryDataArray.Length; i++)
			{
				if (wideSummaryDataArray[i] != null && wideSummaryDataArray[i].DataTbl != null && wideSummaryDataArray[i].DataTbl.Rows.Count > 0)
				{
					outputGroup.OutputDataList.Add(wideSummaryDataArray[i]);
				}
			}
		}
		return outputGroup;
	}

	private WideSummaryData ProcessBinData(StatsResultsBin statBin, List<TestRunInfo> testRuns, Dictionary<string, ParamInfo> discParamInfo, string globalColumnFullName, Dictionary<string, bool> paramVisibilityInfo)
	{
		WideSummaryData wideSummaryData = new WideSummaryData();
		int num = 0;
		List<MergeDataIndicator> mergerCols = new List<MergeDataIndicator>();
		bool flag = false;
		if (statBin.Discriminator1.Count > 0 || statBin.Filter.Count > 0)
		{
			List<DiscGroup> filteredSourceData = DataProcessorUtils.GetFilteredSourceData(statBin, testRuns, statBin.sort);
			List<MergeDataIndicator> list = new List<MergeDataIndicator>();
			if (filteredSourceData != null && filteredSourceData.Count() > 0)
			{
				wideSummaryData.DataTbl = new DataTable();
				string value = string.Empty;
				string text = string.Empty;
				if (discParamInfo != null)
				{
					text = string.Join(":", discParamInfo.Keys.ToArray());
					List<string> list2 = new List<string>();
					foreach (KeyValuePair<string, ParamInfo> item in discParamInfo)
					{
						if (item.Value != null)
						{
							if (double.IsNaN(item.Value.Val))
							{
								list2.Add(item.Value.StrVal);
							}
							else
							{
								list2.Add(item.Value.Val.ToString());
							}
						}
					}
					value = string.Join(",", list2.ToArray());
				}
				if (!string.IsNullOrEmpty(value))
				{
					wideSummaryData.DataTbl.Columns.Add(text);
					flag = true;
				}
				num = CalculateMaxHeaderRowCount(statBin.StatsResult);
				wideSummaryData.HeaderRowStartIndex = 0;
				wideSummaryData.HeaderRowStopIndex = num;
				for (int i = 0; i < num; i++)
				{
					wideSummaryData.DataTbl.Rows.Add();
				}
				if (flag)
				{
					list.Add(new MergeDataIndicator
					{
						StartIndex = wideSummaryData.HeaderRowStopIndex + 1,
						EndIndex = filteredSourceData.Count,
						ColumnPointerForMergedRow = 1
					});
					wideSummaryData.MergeRowList = list;
				}
				int num2 = 0;
				for (int j = 0; j < filteredSourceData.Count; j++)
				{
					if ((reportSettings.FailureAnalysis || reportSettings.AllFailureAnalysis) && !filteredSourceData[j].TestItems.Any((TestRunInfo runInfo) => statBin.StatsResult.Any((StatisticsResultDataSet stat) => runInfo.HasParamFailed(stat.resID))))
					{
						continue;
					}
					wideSummaryData.DataTbl.Rows.Add();
					num++;
					int num3 = num - 1;
					if (wideSummaryData.DataTbl.Columns.Contains(text))
					{
						wideSummaryData.DataTbl.Rows[num3][text] = value;
						wideSummaryData.DataTbl.Rows[0][text] = globalColumnFullName;
					}
					if (filteredSourceData[j].ParamsDict == null || filteredSourceData[j].ParamsDict.Count <= 0)
					{
						continue;
					}
					foreach (KeyValuePair<string, ParamInfo> descItem in filteredSourceData[j].ParamsDict)
					{
						if (num2 == 0)
						{
							DataColumnCollection columns = wideSummaryData.DataTbl.Columns;
							KeyValuePair<string, ParamInfo> keyValuePair = descItem;
							if (!columns.Contains(keyValuePair.Key))
							{
								DataColumnCollection columns2 = wideSummaryData.DataTbl.Columns;
								KeyValuePair<string, ParamInfo> keyValuePair2 = descItem;
								columns2.Add(keyValuePair2.Key);
							}
						}
						IEnumerable<DescriptorItem> enumerable = statBin.GetDescriptorItems().Where(delegate(DescriptorItem d)
						{
							string id = d.Id;
							KeyValuePair<string, ParamInfo> keyValuePair13 = descItem;
							return id == keyValuePair13.Key;
						});
						string value2 = string.Empty;
						if (enumerable != null)
						{
							value2 = (from nmeDetails in enumerable
								where !string.IsNullOrEmpty(nmeDetails.Name)
								select nmeDetails.Name).FirstOrDefault();
						}
						if (string.IsNullOrEmpty(value2))
						{
							KeyValuePair<string, ParamInfo> keyValuePair3 = descItem;
							value2 = keyValuePair3.Key;
						}
						DataColumnCollection columns3 = wideSummaryData.DataTbl.Columns;
						KeyValuePair<string, ParamInfo> keyValuePair4 = descItem;
						if (!columns3.Contains(keyValuePair4.Key))
						{
							continue;
						}
						Dictionary<string, ParamInfo> paramsDict = filteredSourceData[j].ParamsDict;
						KeyValuePair<string, ParamInfo> keyValuePair5 = descItem;
						ParamInfo paramInfo = paramsDict[keyValuePair5.Key];
						string empty = string.Empty;
						if (paramInfo != null)
						{
							empty = (double.IsNaN(paramInfo.Val) ? paramInfo.StrVal : paramInfo.Val.ToString());
							DataRow dataRow = wideSummaryData.DataTbl.Rows[num3];
							DataColumnCollection columns4 = wideSummaryData.DataTbl.Columns;
							KeyValuePair<string, ParamInfo> keyValuePair6 = descItem;
							dataRow[columns4.IndexOf(keyValuePair6.Key)] = empty;
							Dictionary<string, bool> paramVisiblityInfo = filteredSourceData[j].ParamVisiblityInfo;
							KeyValuePair<string, ParamInfo> keyValuePair7 = descItem;
							if (paramVisiblityInfo[keyValuePair7.Key])
							{
								DataRow dataRow2 = wideSummaryData.DataTbl.Rows[0];
								DataColumnCollection columns5 = wideSummaryData.DataTbl.Columns;
								KeyValuePair<string, ParamInfo> keyValuePair8 = descItem;
								dataRow2[columns5.IndexOf(keyValuePair8.Key)] = value2;
							}
						}
						else
						{
							KeyValuePair<string, ParamInfo> keyValuePair9 = descItem;
							if (keyValuePair9.Key == "EMPTY_DISC")
							{
								DataRow dataRow3 = wideSummaryData.DataTbl.Rows[0];
								DataColumnCollection columns6 = wideSummaryData.DataTbl.Columns;
								KeyValuePair<string, ParamInfo> keyValuePair10 = descItem;
								dataRow3[columns6.IndexOf(keyValuePair10.Key)] = value2;
							}
							else
							{
								DataRow dataRow4 = wideSummaryData.DataTbl.Rows[0];
								DataColumnCollection columns7 = wideSummaryData.DataTbl.Columns;
								KeyValuePair<string, ParamInfo> keyValuePair11 = descItem;
								int columnIndex = columns7.IndexOf(keyValuePair11.Key);
								KeyValuePair<string, ParamInfo> keyValuePair12 = descItem;
								dataRow4[columnIndex] = keyValuePair12.Key;
							}
						}
					}
					if (num2 == 0)
					{
						wideSummaryData.StatColStartIndex = wideSummaryData.DataTbl.Columns.Count + 1;
					}
					for (int k = 0; k < statBin.StatsResult.Count; k++)
					{
						ProcessResultSet(wideSummaryData, statBin.StatsResult[k], testRuns, filteredSourceData[j].TestItems, num3, mergerCols, j);
					}
					num2++;
				}
				int count = wideSummaryData.DataTbl.Columns.Count;
				RemoveEmptyColumnsFromTable(wideSummaryData.DataTbl, wideSummaryData.HeaderRowStopIndex, wideSummaryData);
				if (count != wideSummaryData.DataTbl.Columns.Count)
				{
					for (int l = 0; l < wideSummaryData.DataTbl.Columns.Count; l++)
					{
						if (wideSummaryData.DataTbl.Columns[l].Caption.StartsWith("Stat"))
						{
							wideSummaryData.StatColStartIndex = l + 1;
							break;
						}
					}
				}
				int count2 = wideSummaryData.DataTbl.Rows.Count;
				int num4 = RemoveEmptyRowsFromTable(wideSummaryData.DataTbl, wideSummaryData.HeaderRowStopIndex);
				if (count2 != wideSummaryData.DataTbl.Rows.Count)
				{
					wideSummaryData.HeaderRowStopIndex -= num4;
					ResetDataViolationDictionaryAfterRowDelete(num4, wideSummaryData);
				}
				wideSummaryData.NumberFormat = fdWideSummaryDescriptor.StatisticsResultsBin.Format;
			}
		}
		return wideSummaryData;
	}

	private void ResetDataViolationDictionaryAfterRowDelete(int deletedRowCount, WideSummaryData wd)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (wd.DataViolationsDict == null || wd.DataViolationsDict.Count <= 0)
		{
			return;
		}
		foreach (KeyValuePair<string, string> item in wd.DataViolationsDict)
		{
			string[] array = item.Key.Split(new string[1] { "__" }, StringSplitOptions.RemoveEmptyEntries);
			int.TryParse(array[0], out var result);
			result -= deletedRowCount;
			dictionary.Add(result + "__" + array[1], item.Value);
		}
		wd.DataViolationsDict = dictionary;
		wd.DataTbl.Namespace = deletedRowCount.ToString();
	}

	private void ProcessResultSet(WideSummaryData wideSummaryData, StatisticsResultDataSet statResultSet, List<TestRunInfo> testRunsAll, List<TestRunInfo> filteredRuns, int rowIndex, List<MergeDataIndicator> mergerCols, int groupIndex)
	{
		if (wideSummaryData == null || testRunsAll == null || testRunsAll.Count <= 0)
		{
			return;
		}
		if (statResultSet.testID.StartsWith("TestName") && statResultSet.resID == "ParameterName")
		{
			IEnumerable<DescriptorItem> descriptorItems = statResultSet.GetDescriptorItems();
			DescriptorItem descriptorItem = new DescriptorItem();
			if (descriptorItems == null)
			{
				return;
			}
			descriptorItem = descriptorItems.FirstOrDefault((DescriptorItem dsc) => dsc.Id == "EMPTY_DISC");
			if (descriptorItem != null)
			{
				string text = (string.IsNullOrEmpty(descriptorItem.Name) ? descriptorItem.Id : descriptorItem.Name);
				if (!wideSummaryData.DataTbl.Columns.Contains(text))
				{
					wideSummaryData.DataTbl.Columns.Add(text);
					wideSummaryData.DataTbl.Columns[text].Caption = "EMPTY_DISC";
					wideSummaryData.DataTbl.Rows[0][wideSummaryData.DataTbl.Columns.IndexOf(text)] = text;
					wideSummaryData.DataTbl.Rows[rowIndex][wideSummaryData.DataTbl.Columns.IndexOf(text)] = string.Empty;
				}
			}
			return;
		}
		List<DiscGroup> filteredSourceData = DataProcessorUtils.GetFilteredSourceData(statResultSet, testRunsAll, statResultSet.sort);
		List<DiscGroup> filteredSourceData2 = DataProcessorUtils.GetFilteredSourceData(statResultSet, filteredRuns, statResultSet.sort);
		bool flag = false;
		IEnumerable<DescriptorItem> descriptorItems2 = statResultSet.GetDescriptorItems();
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (descriptorItems2 != null && descriptorItems2.Count() > 0)
		{
			IEnumerable<DescriptorItem> enumerable = descriptorItems2.Where((DescriptorItem getFilter) => getFilter.IsFilter);
			if (enumerable != null && enumerable.Count() > 0)
			{
				IEnumerable<DescriptorItem> enumerable2 = from p in enumerable
					group p by new { p.Depth, p.Id } into g
					select g.First();
				if (enumerable2 != null && enumerable2.Count() < enumerable.Count())
				{
					flag = true;
					string groupName;
					foreach (DescriptorItem distinctDiscItem in enumerable2)
					{
						groupName = string.Empty;
						if (dictionary.ContainsKey(distinctDiscItem.Id))
						{
							continue;
						}
						IEnumerable<IEnumerable<DescriptorItem>> enumerable3 = from p in descriptorItems2
							group p by new { p.Depth, p.Id } into gName
							select from gN in gName
								where gN.Id == distinctDiscItem.Id
								select gN;
						enumerable3.ForEach(delegate(IEnumerable<DescriptorItem> grp)
						{
							grp.ForEach(delegate(DescriptorItem str)
							{
								string text4 = groupName;
								groupName = text4 + " " + str.Id + ":" + str.Value;
							});
						});
						dictionary.Add(distinctDiscItem.Id, groupName);
					}
				}
			}
		}
		if (filteredSourceData == null)
		{
			return;
		}
		int num = 0;
		int num2 = 0;
		Dictionary<int, string> dictionary2 = new Dictionary<int, string>();
		foreach (DiscGroup item in filteredSourceData)
		{
			num = wideSummaryData.DataTbl.Columns.Count + 1;
			if (statResultSet.StatsTypes == null || statResultSet.StatsTypes.Count() <= 0)
			{
				continue;
			}
			foreach (StatsType statsType in statResultSet.StatsTypes)
			{
				string text2 = statsType.id + " : " + statResultSet.testID + " : " + statResultSet.resID + " : " + item.GrpNameWithInvisibleDisc;
				if (wideSummaryData == null || wideSummaryData.DataTbl == null || wideSummaryData.DataTbl.Columns.Contains(text2))
				{
					continue;
				}
				wideSummaryData.DataTbl.Columns.Add(text2);
				wideSummaryData.DataTbl.Columns[text2].Caption = "Stat:" + text2;
				if (item.ParamsDict != null && item.ParamsDict.Count > 0)
				{
					for (int i = 0; i < item.ParamsDict.Count(); i++)
					{
						string text3 = string.Empty;
						if (item.ParamsDict.ElementAt(i).Value != null)
						{
							text3 = (double.IsNaN(item.ParamsDict.ElementAt(i).Value.Val) ? item.ParamsDict.ElementAt(i).Value.StrVal : item.ParamsDict.ElementAt(i).Value.Val.ToString());
						}
						if (item.ParamVisiblityInfo[item.ParamsDict.ElementAt(i).Key])
						{
							if (string.IsNullOrEmpty(text3))
							{
								if (!flag)
								{
									wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = item.ParamsDict.ElementAt(i).Key;
								}
								else if (dictionary.ContainsKey(item.ParamsDict.ElementAt(i).Key))
								{
									wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = dictionary[item.ParamsDict.ElementAt(i).Key];
								}
								else
								{
									wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = item.ParamsDict.ElementAt(i).Key;
								}
							}
							else if (!flag)
							{
								wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = item.ParamsDict.ElementAt(i).Key + ":" + text3;
							}
							else if (dictionary.ContainsKey(item.ParamsDict.ElementAt(i).Key))
							{
								wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = dictionary[item.ParamsDict.ElementAt(i).Key];
							}
							else
							{
								wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = item.ParamsDict.ElementAt(i).Key + ":" + text3;
							}
						}
						if (dictionary2.ContainsKey(i + 1))
						{
							dictionary2[i + 1] = wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)].ToString();
						}
						else
						{
							dictionary2.Add(i + 1, wideSummaryData.DataTbl.Rows[i + 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)].ToString());
						}
					}
				}
				wideSummaryData.DataTbl.Rows[0][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = (string.IsNullOrEmpty(statResultSet.name) ? statResultSet.resID : statResultSet.name);
				wideSummaryData.DataTbl.Rows[wideSummaryData.HeaderRowStopIndex - 1][wideSummaryData.DataTbl.Columns.IndexOf(text2)] = statsType.id;
			}
			if (reportSettings.ShowCustomLimits || reportSettings.AutoLimitDescriptor)
			{
				AddCustomLimitColumns(wideSummaryData.DataTbl, statResultSet.testID + " : " + statResultSet.resID + " : " + item.GrpNameWithInvisibleDisc, wideSummaryData.HeaderRowStopIndex - 1, string.IsNullOrEmpty(statResultSet.name) ? statResultSet.resID : statResultSet.name, dictionary2);
			}
			num2 = wideSummaryData.DataTbl.Columns.Count;
			if (num < num2)
			{
				mergerCols.Add(new MergeDataIndicator
				{
					StartIndex = num,
					EndIndex = num2,
					StartColName = wideSummaryData.DataTbl.Columns[num - 1].ColumnName,
					EndColName = wideSummaryData.DataTbl.Columns[num2 - 1].ColumnName
				});
			}
		}
		string empty = string.Empty;
		List<TestRunInfo> list = null;
		foreach (DiscGroup item2 in filteredSourceData2)
		{
			List<Tuple<string, string, string>> list2 = new List<Tuple<string, string, string>>();
			list = DataProcessorUtils.GetTestFilteredSourceData(new ResultDataSet[1] { statResultSet }, item2.TestItems);
			if ((reportSettings.FailureAnalysis || reportSettings.AllFailureAnalysis) && !item2.TestItems.Any((TestRunInfo runInfo) => runInfo.HasParamFailed(statResultSet.resID)))
			{
				continue;
			}
			foreach (StatsType statsType2 in statResultSet.StatsTypes)
			{
				if (list != null && list.Count > 0)
				{
					empty = statsType2.id + " : " + statResultSet.testID + " : " + statResultSet.resID + " : " + item2.GrpNameWithInvisibleDisc;
					list = list.FindAll((TestRunInfo res) => res.ContainsParam(statResultSet.resID));
					if (list.Any((TestRunInfo tr) => tr.TestName == statResultSet.testID && tr.ContainsParam(statResultSet.resID)) && wideSummaryData.DataTbl.Columns.Contains(empty))
					{
						string value = CalculateStatsForTestRuns(list, statsType2.id, statResultSet, wideSummaryData, wideSummaryData.DataTbl.Rows[rowIndex], empty);
						wideSummaryData.DataTbl.Rows[rowIndex][wideSummaryData.DataTbl.Columns.IndexOf(empty)] = value;
					}
				}
			}
			if (!reportSettings.ShowCustomLimits && !reportSettings.AutoLimitDescriptor)
			{
				continue;
			}
			var source = from res in list
				where res.ContainsParam(statResultSet.resID) && !double.IsNaN(res.GetParamValue(statResultSet.resID).Val) && res.GetParamValue(statResultSet.resID) is OutputParamInfo
				select new { ((OutputParamInfo)res.GetParamValue(statResultSet.resID)).CustomLimits };
			string empty2 = string.Empty;
			string empty3 = string.Empty;
			string empty4 = string.Empty;
			string empty5 = string.Empty;
			int k;
			for (k = 0; k < reportSettings.CustomLimitTypes.Count; k++)
			{
				empty2 = string.Empty;
				empty3 = string.Empty;
				var enumerable4 = from lim in source
					where lim.CustomLimits != null
					select new
					{
						HighLim = lim.CustomLimits.HighLimit.Where((Limit h) => h.Index == reportSettings.CustomLimitTypes[k].Index),
						LowLim = lim.CustomLimits.LowLimit.Where((Limit l) => l.Index == reportSettings.CustomLimitTypes[k].Index)
					};
				empty4 = reportSettings.CustomLimitTypes[k].Name + " Min " + statResultSet.testID + " : " + statResultSet.resID + " : " + item2.GrpNameWithInvisibleDisc;
				empty5 = reportSettings.CustomLimitTypes[k].Name + " Max " + statResultSet.testID + " : " + statResultSet.resID + " : " + item2.GrpNameWithInvisibleDisc;
				if (enumerable4 != null && enumerable4.Count() > 0)
				{
					if (enumerable4.First().HighLim != null && enumerable4.First().HighLim.Count() > 0)
					{
						wideSummaryData.DataTbl.Rows[rowIndex][wideSummaryData.DataTbl.Columns.IndexOf(empty5)] = enumerable4.First().HighLim.First().Val;
						empty3 = enumerable4.First().HighLim.First().Val;
					}
					if (enumerable4.First().LowLim != null && enumerable4.First().LowLim.Count() > 0)
					{
						wideSummaryData.DataTbl.Rows[rowIndex][wideSummaryData.DataTbl.Columns.IndexOf(empty4)] = enumerable4.First().LowLim.First().Val;
						empty2 = enumerable4.First().LowLim.First().Val;
					}
					list2.Add(new Tuple<string, string, string>(reportSettings.CustomLimitTypes[k].Name, empty2, empty3));
				}
			}
		}
		wideSummaryData.MergeColumnList = mergerCols;
	}

	private void AddCustomLimitColumns(DataTable wideCardDataTable, string colName, int fakeRowNum, string resName, Dictionary<int, string> discGroupNames)
	{
		string uniqueMinCol = string.Empty;
		string uniqueMaxCol = string.Empty;
		for (int i = 0; i < reportSettings.CustomLimitTypes.Count; i++)
		{
			uniqueMinCol = reportSettings.CustomLimitTypes[i].Name + " Min " + colName;
			if (!wideCardDataTable.Columns.Contains(uniqueMinCol))
			{
				wideCardDataTable.Columns.Add(uniqueMinCol);
				wideCardDataTable.Columns[uniqueMinCol].ExtendedProperties.Add("Color", reportSettings.CustomLimitTypes[i].Color);
				wideCardDataTable.Rows[fakeRowNum][uniqueMinCol] = reportSettings.CustomLimitTypes[i].Name + " Min";
				wideCardDataTable.Rows[0][uniqueMinCol] = resName;
				wideCardDataTable.Columns[uniqueMinCol].Caption = "limits:" + uniqueMinCol;
				if (discGroupNames != null && discGroupNames.Count > 0)
				{
					discGroupNames.ForEach(delegate(KeyValuePair<int, string> keyVal)
					{
						wideCardDataTable.Rows[keyVal.Key][uniqueMinCol] = keyVal.Value;
					});
				}
			}
			uniqueMaxCol = reportSettings.CustomLimitTypes[i].Name + " Max " + colName;
			if (wideCardDataTable.Columns.Contains(uniqueMaxCol))
			{
				continue;
			}
			wideCardDataTable.Columns.Add(uniqueMaxCol);
			wideCardDataTable.Columns[uniqueMaxCol].ExtendedProperties.Add("Color", reportSettings.CustomLimitTypes[i].Color);
			wideCardDataTable.Rows[fakeRowNum][uniqueMaxCol] = reportSettings.CustomLimitTypes[i].Name + " Max";
			wideCardDataTable.Rows[0][uniqueMaxCol] = resName;
			wideCardDataTable.Columns[uniqueMaxCol].Caption = "limits:" + uniqueMaxCol;
			if (discGroupNames != null && discGroupNames.Count > 0)
			{
				discGroupNames.ForEach(delegate(KeyValuePair<int, string> keyVal)
				{
					wideCardDataTable.Rows[keyVal.Key][uniqueMaxCol] = keyVal.Value;
				});
			}
		}
	}

	private int RemoveEmptyRowsFromTable(DataTable dataTable, int currentHeaderRowStopIndex)
	{
		int num = 0;
		if (dataTable != null)
		{
			List<DataRow> list = new List<DataRow>();
			for (int i = 0; i < dataTable.Rows.Count; i++)
			{
				bool flag = true;
				for (int j = 1; j < dataTable.Columns.Count; j++)
				{
					if (!Convert.IsDBNull(dataTable.Rows[i][j]) && !string.IsNullOrEmpty(dataTable.Rows[i][j].ToString()))
					{
						flag = false;
						break;
					}
				}
				if (flag && i < currentHeaderRowStopIndex)
				{
					list.Add(dataTable.Rows[i]);
					num++;
				}
			}
			list.ForEach(delegate(DataRow dataRow)
			{
				dataTable.Rows.Remove(dataRow);
			});
		}
		return num;
	}

	private void RemoveEmptyColumnsFromTable(DataTable dataTable, int stopIndex, WideSummaryData wd)
	{
		if (dataTable == null)
		{
			return;
		}
		List<DataColumn> list = new List<DataColumn>();
		for (int i = 0; i < dataTable.Columns.Count; i++)
		{
			bool flag = true;
			if (dataTable.Columns[i].Caption == "EMPTY_DISC" || dataTable.Columns[i].Caption == "limits:")
			{
				flag = false;
			}
			else if (!string.IsNullOrEmpty(dataTable.Rows[0][i].ToString()))
			{
				for (int j = stopIndex; j < dataTable.Rows.Count; j++)
				{
					if (!Convert.IsDBNull(dataTable.Rows[j][i]) && !string.IsNullOrEmpty(dataTable.Rows[j][i].ToString()) && !string.IsNullOrWhiteSpace(dataTable.Rows[j][i].ToString()))
					{
						flag = false;
						break;
					}
				}
			}
			if (flag && !dataTable.Columns[i].Caption.StartsWith("EMPTY_DISC"))
			{
				list.Add(dataTable.Columns[i]);
			}
		}
		if (wd.MergeColumnList != null && wd.MergeColumnList.Count > 0 && list.Count > 0)
		{
			foreach (MergeDataIndicator mergeColumn in wd.MergeColumnList)
			{
				for (int k = 0; k < list.Count; k++)
				{
					if (!(list[k].ColumnName == mergeColumn.StartColName))
					{
						continue;
					}
					int r;
					for (r = dataTable.Columns.IndexOf(mergeColumn.StartColName) + 1; r < dataTable.Columns.Count; r++)
					{
						if (list.Any((DataColumn col) => col.ColumnName != dataTable.Columns[r].ColumnName) && !string.IsNullOrEmpty(dataTable.Columns[r].ColumnName))
						{
							mergeColumn.StartColName = dataTable.Columns[r].ColumnName;
							mergeColumn.StartIndex = r;
							break;
						}
					}
				}
			}
			foreach (MergeDataIndicator md in wd.MergeColumnList)
			{
				for (int l = 0; l < list.Count; l++)
				{
					if (!list.Any((DataColumn col) => col.ColumnName == md.EndColName))
					{
						continue;
					}
					int r;
					for (r = dataTable.Columns.IndexOf(md.EndColName) - 1; r > 0; r--)
					{
						if (list.Any((DataColumn col) => col.ColumnName != dataTable.Columns[r].ColumnName) && !string.IsNullOrEmpty(dataTable.Columns[r].ColumnName))
						{
							md.EndColName = dataTable.Columns[r].ColumnName;
							md.EndIndex = r;
							break;
						}
					}
				}
			}
		}
		list.ForEach(delegate(DataColumn dataCol)
		{
			dataTable.Columns.Remove(dataCol);
		});
	}

	private string CalculateStatsForTestRuns(List<TestRunInfo> testRunList, string statsType, StatisticsResultDataSet resultSet, WideSummaryData wideCardSummary, DataRow currentRow, string colName)
	{
		List<double> list = new List<double>();
		double min = double.NaN;
		double max = double.NaN;
		double num = double.NaN;
		double num2 = double.NaN;
		double num3 = double.NaN;
		string result = string.Empty;
		string empty = string.Empty;
		var source = from res in testRunList
			where res.ContainsParam(resultSet.resID) && !double.IsNaN(res.GetParamValue(resultSet.resID).Val) && res.GetParamValue(resultSet.resID) is OutputParamInfo
			select new
			{
				res.GetParamValue(resultSet.resID).Val,
				((OutputParamInfo)res.GetParamValue(resultSet.resID)).MinLimit,
				((OutputParamInfo)res.GetParamValue(resultSet.resID)).MaxLimit,
				((OutputParamInfo)res.GetParamValue(resultSet.resID)).CustomLimits
			};
		var enumerable = from res in testRunList
			where res.ContainsParam(resultSet.resID) && !string.IsNullOrEmpty(res.GetParamValue(resultSet.resID).StrVal) && res.GetParamValue(resultSet.resID) is OutputParamInfo
			select new
			{
				Val = res.GetParamValue(resultSet.resID).StrVal
			};
		if (source.Count() > 0)
		{
			list.AddRange(source.Select(p => p.Val));
			IEnumerable<double> enumerable2 = from p in source
				where !double.IsNaN(p.MinLimit)
				select p.MinLimit;
			if (enumerable2 != null && enumerable2.Count() > 0)
			{
				min = enumerable2.First();
			}
			IEnumerable<double> enumerable3 = from p in source
				where !double.IsNaN(p.MaxLimit)
				select p.MaxLimit;
			if (enumerable3 != null && enumerable3.Count() > 0)
			{
				max = enumerable3.First();
			}
			if (!double.IsNaN(min))
			{
				num = min;
			}
			if (!double.IsNaN(max))
			{
				num2 = max;
			}
		}
		string empty2 = string.Empty;
		string empty3 = string.Empty;
		List<Tuple<string, string, string>> list2 = new List<Tuple<string, string, string>>();
		if (reportSettings.CustomLimitTypes != null)
		{
			int k;
			for (k = 0; k < reportSettings.CustomLimitTypes.Count; k++)
			{
				empty2 = string.Empty;
				empty3 = string.Empty;
				var enumerable4 = from lim in source
					where lim.CustomLimits != null
					select new
					{
						HighLim = lim.CustomLimits.HighLimit.Where((Limit h) => h.Index == reportSettings.CustomLimitTypes[k].Index),
						LowLim = lim.CustomLimits.LowLimit.Where((Limit l) => l.Index == reportSettings.CustomLimitTypes[k].Index)
					};
				if (enumerable4 != null && enumerable4.Count() > 0)
				{
					if (enumerable4.First().HighLim != null && enumerable4.First().HighLim.Count() > 0)
					{
						empty3 = enumerable4.First().HighLim.First().Val;
					}
					if (enumerable4.First().LowLim != null && enumerable4.First().LowLim.Count() > 0)
					{
						empty2 = enumerable4.First().LowLim.First().Val;
					}
					list2.Add(new Tuple<string, string, string>(reportSettings.CustomLimitTypes[k].Name, empty2, empty3));
				}
			}
		}
		if (list.Count > 0)
		{
			list.Sort();
			double num4 = list.Avg();
			double num5 = list[0];
			double num6 = list[list.Count - 1];
			double num7 = list.StandardDeviation();
			double num8 = double.NaN;
			double num9 = double.NaN;
			double num10 = double.NaN;
			double num11 = double.NaN;
			min = (double.IsNaN(min) ? double.NegativeInfinity : min);
			max = (double.IsNaN(max) ? double.PositiveInfinity : max);
			int num12 = list.Where((double dp) => dp >= min && dp <= max).Count();
			num11 = ((num12 <= 0) ? 0.0 : ((double)num12 / (double)list.Count * 100.0));
			if (!double.IsNaN(max) && !double.IsNaN(min))
			{
				num10 = ((!(max - num4 < num4 - min)) ? (num4 - min) : (max - num4));
				num8 = ((!(max - num6 < num5 - min)) ? (num5 - min) : (max - num6));
			}
			else if (!double.IsNaN(max) && double.IsNaN(min))
			{
				num10 = max - num4;
				num8 = max - num6;
			}
			else if (!double.IsNaN(min) && double.IsNaN(max))
			{
				num10 = num4 - min;
				num8 = num5 - min;
			}
			if (!double.IsNaN(num10))
			{
				num9 = num10 / (3.0 * num7);
			}
			switch (statsType)
			{
			case "Min":
				num3 = num;
				break;
			case "Max":
				num3 = num2;
				break;
			case "Yield":
				num3 = num11;
				break;
			case "Avg":
				num3 = num4;
				ValidateStatsForLimitViolation(wideCardSummary, currentRow, colName, min, max, num3, list2);
				break;
			case "Sum":
				num3 = list.Sum();
				break;
			case "Max Value":
				num3 = num6;
				ValidateStatsForLimitViolation(wideCardSummary, currentRow, colName, min, max, num3, list2);
				break;
			case "Min Value":
				num3 = num5;
				ValidateStatsForLimitViolation(wideCardSummary, currentRow, colName, min, max, num3, list2);
				break;
			case "StdDev":
				num3 = num7;
				break;
			case "Median":
				num3 = list.Median();
				ValidateStatsForLimitViolation(wideCardSummary, currentRow, colName, min, max, num3, list2);
				break;
			case "Samples":
				num3 = list.Count;
				break;
			case "Worst Case Margin":
				num3 = num8;
				break;
			case "Mean Margin":
				num3 = num10;
				break;
			case "Cpk":
				num3 = num9;
				break;
			case "Status":
			{
				string violationType = string.Empty;
				if (IsAnyDataPointsViolatingLimits(list, min, max, list2, out violationType))
				{
					string key = CommonFunctions.CreateCellLocatorUsingColumnName(wideCardSummary.DataTbl, currentRow, colName);
					if (!wideCardSummary.DataViolationsDict.ContainsKey(key))
					{
						wideCardSummary.DataViolationsDict[key] = violationType;
					}
					empty = "Fail";
				}
				else
				{
					empty = "Pass";
				}
				result = empty;
				break;
			}
			case "Actual Values":
			{
				List<string> strDatapoints = new List<string>();
				list.ForEach(delegate(double dp)
				{
					strDatapoints.Add(dp.ToString());
				});
				result = string.Join(",", strDatapoints);
				break;
			}
			}
		}
		else if (enumerable.Count() > 0)
		{
			List<string> strVal = new List<string>();
			enumerable.ForEach(val =>
			{
				strVal.Add(val.Val);
			});
			if (statsType == "Actual Values")
			{
				result = string.Join(",", strVal);
			}
		}
		if (statsType != "Status" && statsType != "Actual Values")
		{
			result = ((double.IsNaN(num3) || double.IsInfinity(num3)) ? " " : num3.ToString());
		}
		return result;
	}

	private bool IsAnyDataPointsViolatingLimits(List<double> dataPoints, double min, double max, List<Tuple<string, string, string>> customLimitList, out string violationType)
	{
		violationType = string.Empty;
		if (!reportSettings.ShowCustomLimits && !reportSettings.AutoLimitDescriptor)
		{
			violationType = "0";
			return CommonFunctions.IsAnyDataPointViolatingLimits(dataPoints, min, max);
		}
		if (customLimitList != null && customLimitList.Count > 0)
		{
			int cust;
			for (cust = 0; cust < customLimitList.Count(); cust++)
			{
				double result = double.NaN;
				double result2 = double.NaN;
				string text = string.Empty;
				LimitGroupType limitGroupType = reportSettings.CustomLimitTypes.Find((LimitGroupType c) => c.Name == customLimitList[cust].Item1);
				if (limitGroupType != null)
				{
					text = limitGroupType.Index;
				}
				if (!string.IsNullOrEmpty(customLimitList[cust].Item2))
				{
					double.TryParse(customLimitList[cust].Item2, out result);
				}
				if (!string.IsNullOrEmpty(customLimitList[cust].Item3))
				{
					double.TryParse(customLimitList[cust].Item3, out result2);
				}
				if (CommonFunctions.IsAnyDataPointViolatingLimits(dataPoints, result, result2))
				{
					violationType = text;
					return true;
				}
			}
		}
		return false;
	}

	private void ValidateStatsForLimitViolation(WideSummaryData wideCardData, DataRow row, string statsColName, double min, double max, double statsVal, List<Tuple<string, string, string>> customLimitList)
	{
		if (!reportSettings.ShowCustomLimits && !reportSettings.AutoLimitDescriptor)
		{
			if (CommonFunctions.IsViolatingLimits(statsVal, min, max))
			{
				string key = CommonFunctions.CreateCellLocatorUsingColumnName(wideCardData.DataTbl, row, statsColName);
				if (!wideCardData.DataViolationsDict.ContainsKey(key))
				{
					wideCardData.DataViolationsDict[key] = "0";
				}
			}
		}
		else
		{
			if (customLimitList == null || customLimitList.Count <= 0)
			{
				return;
			}
			int cust;
			for (cust = 0; cust < customLimitList.Count(); cust++)
			{
				double result = double.NaN;
				double result2 = double.NaN;
				string value = string.Empty;
				LimitGroupType limitGroupType = reportSettings.CustomLimitTypes.Find((LimitGroupType c) => c.Name == customLimitList[cust].Item1);
				if (limitGroupType != null)
				{
					value = limitGroupType.Index;
				}
				if (!string.IsNullOrEmpty(customLimitList[cust].Item2))
				{
					double.TryParse(customLimitList[cust].Item2, out result);
				}
				if (!string.IsNullOrEmpty(customLimitList[cust].Item3))
				{
					double.TryParse(customLimitList[cust].Item3, out result2);
				}
				if (CommonFunctions.IsViolatingLimits(statsVal, result, result2))
				{
					string key2 = CommonFunctions.CreateCellLocatorUsingColumnName(wideCardData.DataTbl, row, statsColName);
					if (!wideCardData.DataViolationsDict.ContainsKey(key2))
					{
						wideCardData.DataViolationsDict[key2] = value;
					}
				}
			}
		}
	}

	private int CalculateMaxHeaderRowCount(ObservableCollection<StatisticsResultDataSet> statsResults)
	{
		int num = 0;
		int num2 = 0;
		if (statsResults != null)
		{
			foreach (StatisticsResultDataSet statsResult in statsResults)
			{
				IEnumerable<string> distinctDiscriminatorNames = statsResult.GetDistinctDiscriminatorNames();
				if (distinctDiscriminatorNames != null && distinctDiscriminatorNames.Count() > 0)
				{
					num = distinctDiscriminatorNames.Where((string ele) => ele != "EMPTY_DISC").Count();
					if (num > num2)
					{
						num2 = num;
					}
				}
			}
			num2++;
			num2++;
		}
		return num2;
	}
}
