using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Xml.Serialization;

namespace QC.QsprShared.Utilities;

public class QTMUtility
{
	public enum IssueType
	{
		ParameterView,
		ThreadIssue
	}

	private static object writeTraceLock = new object();

	private static char[] SpecialCharacters = new char[23]
	{
		'@', '(', ')', '%', '#', '!', '^', '*', '&', '`',
		'~', '?', '<', '>', '/', '\\', '|', '{', '}', '[',
		']', ',', '$'
	};

	private static DateTime lastWriteTime = DateTime.Now;

	private QTMUtility()
	{
	}

	public static bool RemoveSpecialCharacter(string str, out string newStr)
	{
		bool result = false;
		char[] specialCharacters = SpecialCharacters;
		foreach (char c in specialCharacters)
		{
			if (str.IndexOf(c) != -1)
			{
				str = str.Replace(c, ' ');
				result = true;
			}
		}
		newStr = str;
		return result;
	}

	public static object DeepCopy(object serializableObj)
	{
		MemoryStream memoryStream = new MemoryStream();
		BinaryFormatter binaryFormatter = new BinaryFormatter();
		binaryFormatter.Serialize(memoryStream, serializableObj);
		memoryStream.Position = 0L;
		return binaryFormatter.Deserialize(memoryStream);
	}

	public static DateTime GetDateFromString(string date)
	{
		try
		{
			string[] array = date.Split(' ');
			string text = array[0];
			string text2 = array[1];
			string[] array2 = text.Split('-');
			string[] array3 = text2.Split(':');
			if (array3.Length > 3)
			{
				return new DateTime(int.Parse(array2[2]), int.Parse(array2[0]), int.Parse(array2[1]), int.Parse(array3[0]), int.Parse(array3[1]), int.Parse(array3[2]), int.Parse(array3[3]));
			}
			return new DateTime(int.Parse(array2[2]), int.Parse(array2[0]), int.Parse(array2[1]), int.Parse(array3[0]), int.Parse(array3[1]), int.Parse(array3[2]));
		}
		catch
		{
		}
		return DateTime.Now;
	}

	public static void WriteLogMsg(string text, IssueType issueType)
	{
		try
		{
			bool flag = false;
			if (issueType != 0)
			{
				return;
			}
			if (flag)
			{
				lock (writeTraceLock)
				{
					string path = "C:\\Log";
					if (!Directory.Exists(path))
					{
						Directory.CreateDirectory(path);
					}
					TimeSpan timeSpan = DateTime.Now.Subtract(lastWriteTime);
					using StreamWriter streamWriter = new StreamWriter("C:\\Log\\QSPRDebugTrace.txt", append: true);
					streamWriter.WriteLine($"{DateTime.Now:MM/dd/yyyy H:mm:ss:ffff} - Duration(ms): {timeSpan.TotalMilliseconds.ToString()} - {text}");
				}
			}
			lastWriteTime = DateTime.Now;
		}
		catch
		{
		}
	}

	public static void WriteToEventLog(string source, string message)
	{
		try
		{
			if (!EventLog.SourceExists(source))
			{
				EventLog.CreateEventSource(source, "Application");
			}
			EventLog eventLog = new EventLog();
			eventLog.Source = source;
			eventLog.WriteEntry(message);
		}
		catch
		{
		}
	}

	public static string SystemInformation()
	{
		try
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("System Information");
			stringBuilder.AppendLine("Machine Name: " + Environment.MachineName);
			stringBuilder.AppendLine("OS Version: " + Environment.OSVersion);
			stringBuilder.AppendLine("Processor Count: " + Environment.ProcessorCount);
			stringBuilder.AppendLine("System Management Info");
			WqlObjectQuery query = new WqlObjectQuery("select * from win32_OperatingSystem");
			ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
			foreach (ManagementObject item in managementObjectSearcher.Get())
			{
				string text = item["name"].ToString();
				string[] array = text.Split('|');
				string value = array[0];
				stringBuilder.AppendLine(value);
			}
			return stringBuilder.ToString();
		}
		catch
		{
			return Environment.OSVersion.ToString();
		}
	}

	public static bool IsAllConstraintsHaveTwoParts(string listOfconstraints)
	{
		List<string> list = new List<string>(listOfconstraints.Trim().Split(';'));
		foreach (string item in list)
		{
			char[] separator = new char[5] { '=', ',', '.', ':', '-' };
			string[] array = item.Trim().Split(separator);
			if (!string.IsNullOrEmpty(item) && array.GetLength(0) < 2)
			{
				return false;
			}
		}
		return true;
	}

	public static void LoadPluginContainer(ContentControl contentControl, object container)
	{
		if (container is System.Windows.Forms.UserControl)
		{
			WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
			windowsFormsHost.Child = (System.Windows.Forms.UserControl)container;
			contentControl.Content = windowsFormsHost;
		}
		else if (container is System.Windows.Controls.UserControl)
		{
			contentControl.Content = container;
		}
	}

	public static Visibility ConvertBoolVisibilityToWPFVisibility(bool visiblilty)
	{
		Visibility result = Visibility.Visible;
		if (!visiblilty)
		{
			result = Visibility.Collapsed;
		}
		return result;
	}

	public static void Serialize<T>(string filePath, T obj, SerializationTypes serialzationType = SerializationTypes.Xml) where T : class
	{
		using FileStream fileStream = new FileStream(filePath, FileMode.Create);
		switch (serialzationType)
		{
		case SerializationTypes.Xml:
		{
			XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
			xmlSerializer.Serialize(fileStream, obj);
			break;
		}
		case SerializationTypes.Binary:
		{
			IFormatter formatter = new BinaryFormatter();
			formatter.Serialize(fileStream, obj);
			break;
		}
		}
		fileStream.Close();
	}

	public static T Deserialize<T>(string filePath, SerializationTypes serialzationType = SerializationTypes.Xml) where T : class
	{
		T result = null;
		try
		{
			if (File.Exists(filePath))
			{
				using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
				{
					object obj = null;
					switch (serialzationType)
					{
					case SerializationTypes.Xml:
					{
						XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
						obj = xmlSerializer.Deserialize(fileStream);
						break;
					}
					case SerializationTypes.Binary:
					{
						IFormatter formatter = new BinaryFormatter();
						obj = formatter.Deserialize(fileStream);
						break;
					}
					}
					fileStream.Close();
					return obj as T;
				}
			}
		}
		catch (Exception)
		{
			result = null;
		}
		return result;
	}

	public static object Deserialize(string filePath, Type dataType)
	{
		object result = null;
		try
		{
			if (File.Exists(filePath))
			{
				using StreamReader streamReader = new StreamReader(filePath);
				XmlSerializer xmlSerializer = new XmlSerializer(dataType);
				result = xmlSerializer.Deserialize(streamReader);
				streamReader.Close();
			}
		}
		catch
		{
			result = null;
		}
		return result;
	}

	public static T DeserializeString<T>(string stringToDeserialize) where T : class
	{
		T val = null;
		using StringReader stringReader = new StringReader(stringToDeserialize);
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
		object obj = xmlSerializer.Deserialize(stringReader);
		stringReader.Close();
		return obj as T;
	}

	public static string SerializeToString<T>(T obj) where T : class
	{
		string text = null;
		using StringWriter stringWriter = new StringWriter();
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
		xmlSerializer.Serialize(stringWriter, obj);
		stringWriter.Close();
		return stringWriter.ToString();
	}
}
