using System;
using System.IO;

namespace QC.QSPR;

public class PathUtils
{
	public static string ConvertToAbsolute(string basePath, string pathToConvert)
	{
		if (string.IsNullOrEmpty(pathToConvert.Trim()) || string.IsNullOrEmpty(basePath.Trim()) || IsNetworkPath(pathToConvert) || !IsPathRelative(pathToConvert))
		{
			return pathToConvert;
		}
		if (File.Exists(basePath) || (!Directory.Exists(basePath) && Path.GetExtension(basePath) != ""))
		{
			basePath = Path.GetDirectoryName(basePath);
		}
		string uriString = Path.Combine(basePath, pathToConvert);
		Uri uri = new Uri(uriString);
		return ConvertToFilePath(Uri.UnescapeDataString(uri.LocalPath));
	}

	public static string ConvertToRelative(string basePath, string pathToConvert)
	{
		if (string.IsNullOrEmpty(pathToConvert.Trim()) || string.IsNullOrEmpty(basePath.Trim()) || (IsNetworkPath(pathToConvert) && !IsNetworkPath(basePath)) || IsPathRelative(pathToConvert))
		{
			return pathToConvert;
		}
		if (File.Exists(basePath))
		{
			basePath = Path.GetDirectoryName(basePath);
		}
		Uri uri = new Uri(pathToConvert);
		Uri uri2 = (basePath.EndsWith(Path.DirectorySeparatorChar.ToString()) ? new Uri(basePath) : new Uri(basePath + Path.DirectorySeparatorChar));
		Uri uri3 = uri2.MakeRelativeUri(uri);
		return ConvertToFilePath(Uri.UnescapeDataString(uri3.ToString()));
	}

	public static bool IsPathRelative(string path)
	{
		return !Path.IsPathRooted(path);
	}

	public static bool IsNetworkPath(string path)
	{
		return path.StartsWith(Path.DirectorySeparatorChar.ToString() + Path.DirectorySeparatorChar);
	}

	private static string ConvertToFilePath(string uriString)
	{
		string text = uriString;
		if (text.StartsWith("file:///"))
		{
			text = text.Substring(8);
		}
		else if (text.StartsWith("file://"))
		{
			text = text.Substring(7);
		}
		return text.Replace('/', '\\');
	}
}
