using Microsoft.Win32;
using System;
using System.IO;

namespace fms {
	public class FactorioFinder {
		/// <summary>Try and retrieve the path to Factorio.exe from the registry</summary>
		/// <remarks>Registry key is set by Factorio's installer</remarks>
		/// <returns>The full path to Factorio.exe on success, Nothing on failure</returns>
		public static string findFactorioExe() {
			//try registry
			//string path = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Factorio_is1", "DisplayIcon", null);
			string path = null;

			//try 64 bit registry
			RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
			localKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Factorio_is1");
			if(localKey != null)
				path = localKey.GetValue("DisplayIcon").ToString();

			if(path == null) { // try 32 bit registry
				localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
				localKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Factorio_is1");
				if(localKey != null)
					path = localKey.GetValue("DisplayIcon").ToString();
			}

			if(settings.FactorioExePath_Valid(path)) {
				FmsLogger.Log("Found Factorio exe at " + path);
				return path;
			}

			//sadface
			return null;
		}

		/// <summary>
		/// Try and locate factorio's mods folder either relative to the specified Factorio.exe, or
		/// in the user's %APPDATA% folder
		/// </summary>
		/// <param name="factorioExe">Optional full path to Factorio.exe</param>
		/// <returns>Full path to mods folder on success, Nothing on failure</returns>
		public static string findModDir(string factorioExe = null) {
			string modfolder = null;

			//try relative to factorio exe
			if(!string.IsNullOrWhiteSpace(factorioExe)) {
				modfolder = Path.Combine(Directory.GetParent(Path.GetDirectoryName(factorioExe)).Parent.FullName, "mods");
				if(settings.FactorioModsDirectory_Valid(modfolder))
					return modfolder;
			}

			//try appdata
			modfolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Factorio", "mods");
			if(settings.FactorioModsDirectory_Valid(modfolder))
				return modfolder;

			//sadface
			return null;
		}
	}
}