using System.IO;
using System.Xml.Serialization;

namespace QC.QSPRTreeSchemaLibrary;

public static class QSPRTreeSchema
{
	private static string schemaText = string.Empty;

	public static bool IsQSPRTreeFile(string filePath)
	{
		return HasText(filePath, "<SerializeComponents");
	}

	private static bool HasText(string filePath, string text)
	{
		int num = 1024;
		using StreamReader streamReader = new StreamReader(filePath);
		try
		{
			char[] array = new char[num];
			streamReader.ReadBlock(array, 0, num);
			string text2 = new string(array);
			if (text2.ToLower().Contains(text.ToLower()))
			{
				return true;
			}
			return false;
		}
		catch
		{
			return false;
		}
	}

	public static SerializeComponents LoadTree(string filePath)
	{
		using (StreamReader streamReader = new StreamReader(filePath))
		{
			schemaText = string.Empty;
			string text = streamReader.ReadToEnd();
			int num = 0;
			while (num > -1)
			{
				num = text.IndexOf("<?xml-stylesheet", num);
				if (num == -1)
				{
					break;
				}
				int num2 = text.IndexOf("<", num + 1);
				if (num2 == -1)
				{
					break;
				}
				schemaText += text.Substring(num, num2 - num);
				num = num2;
			}
			schemaText = schemaText.Trim();
		}
		return Deserialize<SerializeComponents>(filePath);
	}

	public static void WriteTree(SerializeComponents treeObj, string filePath)
	{
		Serialize(filePath, treeObj);
	}

	private static void Serialize<T>(string filePath, T obj) where T : class
	{
		string text = string.Empty;
		using (MemoryStream memoryStream = new MemoryStream())
		{
			XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
			xmlSerializer.Serialize(memoryStream, obj);
			memoryStream.Seek(0L, SeekOrigin.Begin);
			using (StreamReader streamReader = new StreamReader(memoryStream))
			{
				text = streamReader.ReadToEnd();
			}
			memoryStream.Close();
		}
		int startIndex = text.IndexOf("<SerializeComponents") - 1;
		text = text.Insert(startIndex, schemaText);
		using StreamWriter streamWriter = new StreamWriter(filePath);
		streamWriter.Write(text);
	}

	private static T Deserialize<T>(string filePath) where T : class
	{
		T result = null;
		if (File.Exists(filePath))
		{
			using (StreamReader streamReader = new StreamReader(filePath))
			{
				XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
				object obj = xmlSerializer.Deserialize(streamReader);
				streamReader.Close();
				return obj as T;
			}
		}
		return result;
	}
}
