using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using QC.CTDS.DM.ApplicationsManager;
using QC.CTDS.DM.DataStructures;
using QC.CTDS.DM.DataStructures.FormatDescriptorStructure;
using QC.CTDS.DM.SharedLibrary;

namespace QC.CTDS.DM.ServicePlugins.CommandLineService;

public class DataminerConsole
{
	public const string GenerateReportPowerPointOption = "-ppt";

	public const string GenerateReportFormatDescriptorOption = "-f";

	public const string GenerateReportOutputFile = "-o";

	public const string GenerateReportLimitFile = "-l";

	public const string GenerateReportGroupDiscriminatorName = "-gd";

	public const string GenerateReportChartDiscriminatorName = "-cd";

	public const string GenerateReportSheetDiscriminatorName = "-sd";

	public const string GenerateReportValidateFormatDescriptor = "-v";

	public const string GenerateReportSkipDetailedUnitPlots = "-skipDetail";

	public const string GenerateReportSkipStatsColumns = "-skipStatsColumns";

	public const string GenerateReportSuppressStatisticsPlot = "-ss";

	public const string GenerateReportSuppressUnitDetailsPlot = "-sud";

	public const string GenerateReportSuppressUnitPoints = "-sup";

	public const string GenerateReportSuppressLegends = "-sl";

	public const string GenerateReportSuppressDistributionOverlays = "-so";

	public const string GenerateReportSuppressHistogramBins = "-shb";

	public const string GenerateReportCycleColors = "-cup";

	public const string GenerateReportShowLimitUnits = "-lup";

	public const string GenerateReportShowLimitOnScatterPlots = "-lsp";

	public const string GenerateReportIncludeUnitsInLegend = "-ul";

	public const string GenerateReportReducedSummary = "-reducedsummary";

	public const string GenerateReportFailureAnalysis = "-failureanalysis";

	public const string GenerateReportAllFailureAnalysis = "-allfailureanalysis";

	public const string GenerateReportStaticStatsColumns = "-staticstatscolumns";

	public const string GenerateReportShowSerialNumberInChartData = "-suutid";

	public const string GenerateReportDrawLinesForUnitDataPoints = "-dup";

	public const string GenerateReportSuppressAverage = "-sa";

	public const string GenerateReportEnableVerboseLogging = "-d";

	public const string ExcelToPowerpoint = "-xlstoppt";

	public const string FileFolderGroupDataFilesOption = "-g";

	public const string FileFolderGroupRecussiveFilesOption = "-r";

	public const string IncludeInvalidResults = "-inv";

	public const string RunInSequentialMode = "-sequential";

	public const string GenerateReportVersion = "-version";

	public const string GenerateReportAutoFD = "-autoFD";

	public const string GenerateReportAutoLD = "-autoLD";

	public const string SonarSqlCmdLine = "-sql";

	public const string NoLogDataminerRun = "-nolog";

	public const string OpenOutputFiles = "-openoutfiles";

	public const string HelpOption1 = "-help";

	public const string HelpOption2 = "/?";

	public const string SupressCustomLimitLegend = "-scl";

	public const string PreTransformExpression = "-expr";

	public const string PluginsFolderPathCommandLineOption = "-pluginfolderpath";

	public const string OutputPluginName = "-outputPlugin";

	private static string formatDescriptor = string.Empty;

	private static string outputFile = string.Empty;

	private static string limitFile = string.Empty;

	private static string chartDiscriminatorName = string.Empty;

	private static string sheetDiscriminatorName = string.Empty;

	private static string groupDiscriminatorName = string.Empty;

	private static ConsoleLogger logger = new ConsoleLogger();

	private static TextLogger textLogger = new TextLogger();

	private static ReportGenerator reportGenerator;

	private static FileSystemItemsGroupingCollection groupingColl = new FileSystemItemsGroupingCollection();

	public static void Main(string[] args)
	{
		if (args.Length == 1)
		{
			if (args[0] == "-version")
			{
				WriteVersionInformation();
			}
			if (args[0] == "-help" || args[0] == "/?")
			{
				WriteHelp();
			}
			return;
		}
		if (args.Length == 0)
		{
			WriteVersionInformation();
			WriteHelp();
			return;
		}
		CleanupLogFolder();
		logger.WriteLog("Using dataminer.net for report generation", LogType.Verbose);
		textLogger.WriteLog("Using dataminer.net for report generation", LogType.Verbose);
		new List<string>();
		string pluginsFolderPath = GetPluginsFolderPath(args);
		if (string.IsNullOrEmpty(pluginsFolderPath))
		{
			reportGenerator = new ReportGenerator();
		}
		else
		{
			logger.WriteLog("Using custom plugin folder path = " + pluginsFolderPath, LogType.Verbose);
			textLogger.WriteLog("Using custom plugin folder path = " + pluginsFolderPath, LogType.Verbose);
			reportGenerator = new ReportGenerator(pluginsFolderPath);
		}
		ParseCommandLineArgs(args.ToList());
		reportGenerator.LoggerList.Add(logger);
		reportGenerator.LoggerList.Add(textLogger);
		reportGenerator.ReportEnviornment = string.Join(" ", args);
		reportGenerator.ServicePluginVersion = CommonFunctions.GetAssemblyVersion(Assembly.GetExecutingAssembly());
		if (!string.IsNullOrEmpty(formatDescriptor))
		{
			reportGenerator.LoadDescriptor(formatDescriptor);
		}
		reportGenerator.SetInputFormat("SuiteSchemaInputPlugin");
		if (string.IsNullOrEmpty(reportGenerator.ReportSettingsInfo.SonarSql))
		{
			reportGenerator.LoadSourceData(groupingColl);
		}
		else
		{
			reportGenerator.LoadAutoSourceData();
		}
		if (!args.Contains("-nolog"))
		{
			Task.Factory.StartNew(delegate
			{
				LogDataminerRun(string.Join(" ", args), Assembly.GetExecutingAssembly().Location);
			});
		}
		textLogger.WriteLog("Dataminer Command : " + reportGenerator.ReportEnviornment, LogType.Verbose);
		if (string.IsNullOrEmpty(reportGenerator.ReportSettingsInfo.OutputPluginName))
		{
			reportGenerator.GenerateReport("ExcelFormatter", outputFile, IsCallerDataminer: true);
		}
		else
		{
			reportGenerator.GenerateReport(reportGenerator.ReportSettingsInfo.OutputPluginName, outputFile, IsCallerDataminer: true);
		}
	}

	private static string GetPluginsFolderPath(string[] args)
	{
		string result = null;
		for (int i = 0; i < args.Length; i++)
		{
			if (string.Compare(args[i], "-pluginfolderpath", ignoreCase: true) == 0)
			{
				if (Directory.Exists(args[i + 1]))
				{
					result = args[i + 1];
				}
				break;
			}
		}
		return result;
	}

	public static void CleanupLogFolder()
	{
		string logDir = Constants.DefaultTempFilePath + "\\Logs";
		Action<string, TimeSpan> cleanupTempFolderAction = CleanupQMineTempFolder;
		TimeSpan cleanUpDuration = default(TimeSpan);
		ref TimeSpan reference = ref cleanUpDuration;
		reference = new TimeSpan(0, Constants.LogFileCleanupInterval, 0, 0);
		Task.Factory.StartNew(delegate
		{
			cleanupTempFolderAction(logDir, cleanUpDuration);
		});
	}

	private static void CleanupQMineTempFolder(string path, TimeSpan duration)
	{
		try
		{
			if (!Directory.Exists(path))
			{
				return;
			}
			DirectoryInfo directoryInfo = new DirectoryInfo(path);
			IEnumerable<FileInfo> enumerable = from file in directoryInfo.GetFiles()
				where file.LastWriteTime.Add(duration) < DateTime.Now
				select file;
			if (enumerable != null && enumerable.Count() > 0)
			{
				enumerable.ForEach(delegate(FileInfo file)
				{
					file.Delete();
				});
			}
		}
		catch (Exception ex)
		{
			logger.WriteLog(ex.ToString(), LogType.Error);
		}
	}

	private static void WriteVersionInformation()
	{
		logger.WriteLog("Dataminer.net version: " + CommonFunctions.GetAssemblyVersion(Assembly.GetExecutingAssembly()), LogType.Verbose);
	}

	private static void WriteHelp()
	{
		string empty = string.Empty;
		empty = "\nUSAGE:  \n    DataMiner <source>... [Options] <formatDesc> \n    DataMiner [-g <groupName> <source>]... <formatDesc> \n    DataMiner [-gd <discriminator>] <source>... <formatDesc> \n    Dataminer -r \"C:\\Temp\\DataFiles\" -o \"C:\\Temp\\OutputFile.xlsx\" -lup - sl -f \"C:\\FormatDescriptor.xml\"\n  Options: \n    -g <groupName>         Creates groups of data. \n                           <groupName> is used to assign names to the groups \n    -gd <discriminator>    Groups data based on specified discriminator. \n                           <discriminator> can be id or id:val ( Band or Band:=1 ) \n    -cd <discriminator>    Similar to -gd, but creates new charts for each discriminated value \n    -sd <discriminator>    Similar to -gd, but creates new worksheets for each discriminated value \n    -o <output file name>  Saves the output to the specified file. \n    -openoutfiles          Opens the generated output file before dataminer exits. \n    -f <formatDesc>        Allows you to format descriptor \n    -l<LimitDesc><LimitType> Allows you to specify a limit descriptor file and optionally pick limit type \n    -autoFD                Grab FormatDescriptors automatically \n    -autoLD<LimitType>     Grab LimitDescriptors automatically and optionally pick limit type \n    -nopre                 Ignore Format Descriptor XSL Transformation before Processing \n    -ss                    Suppress statistics plot on all binned chart groups \n    -sud                   Suppress unit detail plot on all binned chart groups \n    -sup                   Suppress unit points on all binned chart groups \n    -sl                    Suppress legend on all charts \n    -so                    Suppress distribution overlays on histogram plots \n    -cup                   Cycle colors on unit data points \n    -lup                   Show limits unit data points \n    -lsp                   Show limits scatter plots \n    -suutid                Show serial number and run id in chart data tables \n    -dup                   Draw lines for unit series in line chart \n    -ul                    Unit legend - included all units in legend \n    -inv                   Include results marked \"invalid\" when processing data \n    -sa                    Suppress average series \n    -shb                   Suppress histogram bins on histogram plots \n    -failureanalysis       Show failure analysis only for condensed summary \n    -allfailureanalysis    Show failure analysis for all chart types \n    -generateSummary       Generates unit summary worksheet \n    -skipDetail            Do not generate detailed units plots \n    -skipStatsColumns      Do not include stats columns in summary tables \n    -scl                  Suppress the custom limits legends on line charts\n    -expr<Operand1, Operand2, Operator>\t\tPre Data Transformation plugin\n    -delimiter<delimiterStringInQuotes> used in conjunction with -outputPlugin CSVFormatter to specify a delimiter  Note:  When specifying a directory as a <source> argument all files in that directory will be processed.";
		logger.WriteLog(empty, LogType.Verbose);
	}

	private static void LogDataminerRun(string commandLineArgs, string commandPath)
	{
		string connectionString = "Data Source=ctedba\\sql2k8;Initial Catalog=QMonDB;User ID=qminewriter;Password=$QM2014";
		string machineName = Environment.MachineName;
		string text = DateTime.Now.ToString();
		string text2 = "Dataminer.net";
		using SqlConnection sqlConnection = new SqlConnection(connectionString);
		string cmdText = string.Format("INSERT INTO tblDataminerRunlogs(MachineName, DataminerEngine, CommandPath, CommandLineArgs, RunDateTime) VALUES('{0}','{1}', '{2}', '{3}','{4}')", machineName, text2, commandPath.Replace("'", "\""), commandLineArgs.Replace("'", "\""), text);
		SqlCommand sqlCommand = new SqlCommand(cmdText, sqlConnection);
		sqlConnection.Open();
		sqlCommand.ExecuteNonQuery();
		sqlConnection.Close();
	}

	private static string GetCommandLineValue(int currentPosition, List<string> cmdLineArgsList)
	{
		string result = string.Empty;
		int num = currentPosition + 1;
		if (num < cmdLineArgsList.Count)
		{
			result = cmdLineArgsList[num];
		}
		return result;
	}

	private static bool IsFilePathValid(string filePath)
	{
		bool flag = false;
		try
		{
			if (Directory.Exists(Path.GetDirectoryName(filePath)))
			{
				return true;
			}
			Directory.CreateDirectory(Path.GetDirectoryName(filePath));
			return true;
		}
		catch (Exception)
		{
			return false;
		}
	}

	private static bool ParseCommandLineArgs(List<string> cmdLineArgsList)
	{
		bool flag = true;
		string empty = string.Empty;
		string text = string.Empty;
		_ = string.Empty;
		string empty2 = string.Empty;
		string groupName = string.Empty;
		bool isRecurssive = false;
		for (int i = 0; i < cmdLineArgsList.Count; i++)
		{
			if (cmdLineArgsList[i].StartsWith("-"))
			{
				groupName = string.Empty;
			}
			if (flag)
			{
				if (cmdLineArgsList[i].Equals("-inv", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.IncludeInvalidResults = true;
				}
				else if (cmdLineArgsList[i].Equals("-f", StringComparison.InvariantCultureIgnoreCase))
				{
					text = GetCommandLineValue(i, cmdLineArgsList);
					if (IsFilePathValid(text))
					{
						formatDescriptor = text;
					}
					else
					{
						flag = false;
						logger.WriteLog("Format descriptor path " + text + " is invalid ", LogType.Error);
					}
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-o", StringComparison.InvariantCultureIgnoreCase))
				{
					empty = GetCommandLineValue(i, cmdLineArgsList);
					if (IsFilePathValid(empty))
					{
						outputFile = empty;
					}
					else
					{
						outputFile = string.Empty;
					}
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-l", StringComparison.InvariantCultureIgnoreCase))
				{
					empty2 = GetCommandLineValue(i, cmdLineArgsList);
					if (IsFilePathValid(empty2))
					{
						limitFile = empty2;
						reportGenerator.ReportSettingsInfo.ShowCustomLimits = true;
						reportGenerator.LoadLimitDescriptor(limitFile);
						string commandLineValue = GetCommandLineValue(i + 1, cmdLineArgsList);
						if (!string.IsNullOrEmpty(commandLineValue) && !commandLineValue.StartsWith("-"))
						{
							reportGenerator.ReportSettingsInfo.LimitTypes = commandLineValue;
						}
					}
					else
					{
						flag = false;
						logger.WriteLog("Limit descriptor path " + empty2 + " is invalid ", LogType.Error);
					}
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-cd", StringComparison.InvariantCultureIgnoreCase))
				{
					string commandLineValue2 = GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue2))
					{
						reportGenerator.ReportSettingsInfo.ChartDiscriminator = CreateDiscriminator(reportGenerator.ReportSettingsInfo.ChartDiscriminator, commandLineValue2);
					}
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-sd", StringComparison.InvariantCultureIgnoreCase))
				{
					string commandLineValue3 = GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue3))
					{
						reportGenerator.ReportSettingsInfo.SheetDiscriminator = CreateDiscriminator(reportGenerator.ReportSettingsInfo.SheetDiscriminator, commandLineValue3);
					}
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-gd", StringComparison.InvariantCultureIgnoreCase))
				{
					string commandLineValue4 = GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue4))
					{
						reportGenerator.ReportSettingsInfo.GroupDiscriminator = CreateDiscriminator(reportGenerator.ReportSettingsInfo.GroupDiscriminator, commandLineValue4);
					}
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-sql", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SonarSql = cmdLineArgsList[++i];
				}
				else if (cmdLineArgsList[i].Equals("-openoutfiles", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.OpenOutputFiles = true;
				}
				else if (cmdLineArgsList[i].Equals("-scl", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SupressCustomLimitLegend = true;
				}
				else if (cmdLineArgsList[i].Equals("-sequential", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.RunInSequentialMode = true;
				}
				else if (cmdLineArgsList[i].Equals("-skipDetail", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SkipDetailedUnitPlots = true;
				}
				else if (cmdLineArgsList[i].Equals("-skipStatsColumns", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SkipStatsColumns = true;
				}
				else if (cmdLineArgsList[i].Equals("-ss", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressStatisticsPlot = true;
				}
				else if (cmdLineArgsList[i].Equals("-sud", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressUnitDetailsPlot = true;
				}
				else if (cmdLineArgsList[i].Equals("-sup", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressUnitPoints = true;
				}
				else if (cmdLineArgsList[i].Equals("-sl", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressLegends = true;
				}
				else if (cmdLineArgsList[i].Equals("-so", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressDistributionOverlays = true;
				}
				else if (cmdLineArgsList[i].Equals("-shb", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressHistogramBins = true;
				}
				else if (cmdLineArgsList[i].Equals("-cup", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.CycleColors = true;
				}
				else if (cmdLineArgsList[i].Equals("-lup", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.ShowLimitUnits = true;
				}
				else if (cmdLineArgsList[i].Equals("-lsp", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.ShowLimitOnScatterPlots = true;
				}
				else if (cmdLineArgsList[i].Equals("-ul", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.IncludeUnitsInLegend = true;
				}
				else if (cmdLineArgsList[i].Equals("-reducedsummary", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.ReducedSummary = true;
				}
				else if (cmdLineArgsList[i].Equals("-failureanalysis", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.FailureAnalysis = true;
				}
				else if (cmdLineArgsList[i].Equals("-allfailureanalysis", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.AllFailureAnalysis = true;
				}
				else if (cmdLineArgsList[i].Equals("-staticstatscolumns", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.StaticStatsColumns = true;
				}
				else if (cmdLineArgsList[i].Equals("-suutid", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.ShowSerialNumberInChartData = true;
				}
				else if (cmdLineArgsList[i].Equals("-dup", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.DrawLinesForUnitDataPoints = true;
				}
				else if (cmdLineArgsList[i].Equals("-sa", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.SuppressAverageSeries = true;
				}
				else if (cmdLineArgsList[i].Equals("-d", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.EnableVerboseLoggingMode = true;
				}
				else if (cmdLineArgsList[i].Equals("-autoFD", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.AutoFormatDescriptor = true;
				}
				else if (cmdLineArgsList[i].Equals("-autoLD", StringComparison.InvariantCultureIgnoreCase))
				{
					reportGenerator.ReportSettingsInfo.AutoLimitDescriptor = true;
					string commandLineValue5 = GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue5) && !commandLineValue5.StartsWith("-") && !File.Exists(commandLineValue5) && !Directory.Exists(commandLineValue5))
					{
						reportGenerator.ReportSettingsInfo.LimitTypes = commandLineValue5;
					}
				}
				else if (cmdLineArgsList[i].Equals("-g", StringComparison.InvariantCultureIgnoreCase))
				{
					groupName = cmdLineArgsList[i + 1];
					i++;
				}
				else if (cmdLineArgsList[i].Equals("-r", StringComparison.InvariantCultureIgnoreCase))
				{
					isRecurssive = true;
				}
				else if (cmdLineArgsList[i].Equals("-expr", StringComparison.InvariantCultureIgnoreCase))
				{
					string commandLineValue6 = GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue6) && !commandLineValue6.StartsWith("-"))
					{
						reportGenerator.ReportSettingsInfo.PreTransformExpressions = commandLineValue6;
					}
				}
				else if (cmdLineArgsList[i].Equals("-outputPlugin", StringComparison.InvariantCultureIgnoreCase))
				{
					string commandLineValue7 = GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue7))
					{
						reportGenerator.ReportSettingsInfo.OutputPluginName = commandLineValue7;
					}
				}
				else if (cmdLineArgsList[i].Equals(Constants.DelimiterString, StringComparison.InvariantCultureIgnoreCase))
				{
					string commandLineValue8 = CommonFunctions.GetCommandLineValue(i, cmdLineArgsList);
					if (!string.IsNullOrEmpty(commandLineValue8))
					{
						reportGenerator.ReportSettingsInfo.Delimiter = commandLineValue8;
					}
				}
				else if (i == cmdLineArgsList.Count - 1 && string.IsNullOrEmpty(text) && !reportGenerator.ReportSettingsInfo.AutoFormatDescriptor)
				{
					if (File.Exists(cmdLineArgsList[i]))
					{
						formatDescriptor = cmdLineArgsList[i];
					}
				}
				else
				{
					if (cmdLineArgsList[i].StartsWith("-"))
					{
						continue;
					}
					List<string> list = new List<string>();
					for (int j = i; j < cmdLineArgsList.Count; j++)
					{
						if (j == cmdLineArgsList.Count - 1 && string.IsNullOrEmpty(text) && !reportGenerator.ReportSettingsInfo.AutoFormatDescriptor)
						{
							i = j - 1;
							break;
						}
						if (cmdLineArgsList[j].StartsWith("-"))
						{
							i = j - 1;
							break;
						}
						if (File.Exists(cmdLineArgsList[j]) || Directory.Exists(cmdLineArgsList[j]))
						{
							list.Add(cmdLineArgsList[j]);
						}
					}
					if (list.Count > 0)
					{
						AddGroupFiles(groupName, list, isRecurssive);
					}
				}
				continue;
			}
			return flag;
		}
		return flag;
	}

	private static Discriminator CreateDiscriminator(Discriminator disc, string discCommandLineStr)
	{
		Discriminator discriminator = null;
		string discId = string.Empty;
		string text = ParseDiscriminatorString(discCommandLineStr, ref discId);
		if (!string.IsNullOrEmpty(discId))
		{
			discriminator = new Discriminator();
			discriminator.id = discId;
			if (!string.IsNullOrEmpty(text))
			{
				discriminator.disValue = text;
			}
			if (disc == null)
			{
				disc = discriminator;
			}
			else
			{
				Discriminator discriminator2 = disc;
				while (discriminator2.Discriminator1.Count > 0)
				{
					discriminator2 = discriminator2.Discriminator1[0];
				}
				discriminator2.Discriminator1.Add(discriminator);
			}
		}
		return disc;
	}

	private static string ParseDiscriminatorString(string discCommandLineStr, ref string discId)
	{
		string result = string.Empty;
		int num = -1;
		if (discCommandLineStr.Contains(">="))
		{
			num = discCommandLineStr.IndexOf(">=");
		}
		else if (discCommandLineStr.Contains("<="))
		{
			num = discCommandLineStr.IndexOf("<=");
		}
		else if (discCommandLineStr.Contains("!="))
		{
			num = discCommandLineStr.IndexOf("!=");
		}
		else if (discCommandLineStr.Contains(":="))
		{
			discCommandLineStr = discCommandLineStr.Replace(":", "");
			num = discCommandLineStr.IndexOf("=");
		}
		else if (discCommandLineStr.Contains("="))
		{
			num = discCommandLineStr.IndexOf("=");
		}
		else if (discCommandLineStr.Contains(">"))
		{
			num = discCommandLineStr.IndexOf(">");
		}
		else if (discCommandLineStr.Contains("<"))
		{
			num = discCommandLineStr.IndexOf("<");
		}
		else
		{
			discId = discCommandLineStr;
		}
		if (num > 0)
		{
			result = discCommandLineStr.Substring(num, discCommandLineStr.Length - num);
			discId = discCommandLineStr.Substring(0, num);
		}
		return result;
	}

	private static void AddGroupFiles(string groupName, List<string> fileFolderList, bool isRecurssive)
	{
		List<FileSystemItem> list = new List<FileSystemItem>();
		AddFoldersAndFiles(fileFolderList.ToArray(), addingDataFiles: true, list, isRecurssive);
		if (groupingColl.FileSystemItemsGroupList != null && groupingColl.FileSystemItemsGroupList.Count == 0 && string.IsNullOrEmpty(groupName))
		{
			groupingColl.FileSystemItemsGroupList.Add(new FileSystemItemsGroup());
			groupingColl.FileSystemItemsGroupList[0].FileSystemItemsList = list;
		}
		else if (!string.IsNullOrEmpty(groupName))
		{
			FileSystemItemsGroup fileSystemItemsGroup = groupingColl.FileSystemItemsGroupList.Find((FileSystemItemsGroup gpItem) => gpItem.GroupName == groupName);
			if (fileSystemItemsGroup != null)
			{
				fileSystemItemsGroup.FileSystemItemsList.AddRange(list);
				return;
			}
			groupingColl.FileSystemItemsGroupList.Add(new FileSystemItemsGroup
			{
				FileSystemItemsList = list,
				GroupName = groupName
			});
		}
	}

	private static void AddFoldersAndFiles(string[] files, bool addingDataFiles, List<FileSystemItem> coll, bool includeSubFolder)
	{
		List<string> list = new List<string>();
		List<string> list2 = new List<string>();
		foreach (string text in files)
		{
			FileAttributes attributes = File.GetAttributes(text);
			if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
			{
				list2.Add(text);
			}
			else
			{
				list.Add(text);
			}
		}
		if (list.Count > 0)
		{
			AddFiles(list.ToArray(), addingDataFiles: true, coll);
		}
		if (list2.Count <= 0)
		{
			return;
		}
		foreach (string item in list2)
		{
			AddFolder(coll, item, includeSubFolder);
		}
	}

	private static void AddFiles(string[] sourceFiles, bool addingDataFiles, List<FileSystemItem> coll)
	{
		foreach (string text in sourceFiles)
		{
			if (Path.GetExtension(text) == ".cxml")
			{
				logger.WriteLog("This file is compressed! Decompressing...", LogType.Verbose);
				string fullPath = CommonFunctions.DecompressCXML(text);
				coll.Add(new FileSystemItem
				{
					FullPath = fullPath
				});
			}
			else
			{
				coll.Add(new FileSystemItem
				{
					FullPath = text
				});
			}
		}
	}

	private static void AddFolder(List<FileSystemItem> coll, string dir, bool includeSubFolder)
	{
		logger.WriteLog("Adding Folder..", LogType.Verbose);
		DirectoryInfo directoryInfo = new DirectoryInfo(dir);
		FolderItem folderItem = new FolderItem();
		folderItem.FullPath = directoryInfo.FullName;
		FolderItem folderItem2 = folderItem;
		if (includeSubFolder)
		{
			folderItem2.IncludeSubFolders = true;
			if (groupingColl.FileSystemItemsGroupList.Any((FileSystemItemsGroup grp) => string.IsNullOrEmpty(grp.GroupName)))
			{
				groupingColl.FileSystemItemsGroupList.Where((FileSystemItemsGroup grp) => string.IsNullOrEmpty(grp.GroupName)).First().FileSystemItemsList.Add(folderItem2);
			}
			else
			{
				coll.Add(folderItem2);
			}
		}
		else
		{
			coll.Add(folderItem2);
		}
	}
}
