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

namespace WPF_ScanControl_Sample
{
    public static class CustomDllResolver
    {
        private static readonly string[] SDK_DLL_WHITELIST = { "PPScanControl.dll", "TwainDotNet.dll" };

        /// <summary>
        /// Call this method at the beginning of the program.
        /// </summary>
        public static void InitializeAssembly(string absoluteFolder)
        {
            // Handle event for unmanaged dll loading.
            string exeFolder = AppDomain.CurrentDomain.BaseDirectory;
            if (exeFolder != absoluteFolder)
                Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + absoluteFolder);

            // Handle event for mananged dll loading.
            AppDomain.CurrentDomain.AssemblyResolve += delegate (object sender, ResolveEventArgs args)
            {
                string assemblyFile = args.Name.Contains(',')
                    ? args.Name.Substring(0, args.Name.IndexOf(','))
                    : args.Name;

                assemblyFile += ".dll";

                // Forbid non handled dll's
                if (!SDK_DLL_WHITELIST.Contains(assemblyFile))
                {
                    return null;
                }

                string targetPath = Path.Combine(absoluteFolder, assemblyFile);

                try
                {
                    return Assembly.LoadFile(targetPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return null;
                }
            };
        }
    }
}
