using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
namespace StardewModdingApi.Installer
{
    /// The entry point for SMAPI's install and uninstall console app.
    internal class Program
    {
        /*********
        ** Properties
        *********/
        /// The absolute path to search for referenced assemblies.
        [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute", Justification = "The assembly location is never null in this context.")]
        private static readonly string DllSearchPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "smapi-internal");
        /*********
        ** Public methods
        *********/
        /// Run the install or uninstall script.
        /// The command line arguments.
        public static void Main(string[] args)
        {
            // set up assembly resolution
            AppDomain.CurrentDomain.AssemblyResolve += Program.CurrentDomain_AssemblyResolve;
            // launch installer
            var installer = new InteractiveInstaller();
            installer.Run(args);
        }
        /*********
        ** Private methods
        *********/
        /// Method called when assembly resolution fails, which may return a manually resolved assembly.
        /// The event sender.
        /// The event arguments.
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
        {
            try
            {
                AssemblyName name = new AssemblyName(e.Name);
                foreach (FileInfo dll in new DirectoryInfo(Program.DllSearchPath).EnumerateFiles("*.dll"))
                {
                    if (name.Name.Equals(AssemblyName.GetAssemblyName(dll.FullName).Name, StringComparison.InvariantCultureIgnoreCase))
                        return Assembly.LoadFrom(dll.FullName);
                }
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error resolving assembly: {ex}");
                return null;
            }
        }
    }
}