using System;
using System.IO;
using System.Reflection;

namespace SharedUtility
{
    internal static class AssemblyResolveInMyAround
    {
        /// <summary>
        /// Patch assembly version range
        /// </summary>
        public static void Register()
        {
            var executingAssemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new InvalidOperationException("Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) is null");

            AppDomain.CurrentDomain.AssemblyResolve += delegate (object sender, ResolveEventArgs args)
            {
                var pathWithoutExtension = Path.Combine(executingAssemblyDir, new AssemblyName(args.Name).Name);

                var asmPath = pathWithoutExtension + ".dll";
                if (File.Exists(asmPath)) return Assembly.LoadFrom(asmPath);

                asmPath = pathWithoutExtension + ".exe";
                if (File.Exists(asmPath)) return Assembly.LoadFrom(asmPath);

                return null;
            };
        }
    }
}
