using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32.SafeHandles; 

namespace RogerMfReaderExample
{
    public class loadRogerLibrary
    {

        // ******************************************************************************
        // API functions
        // ******************************************************************************
        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private extern static IntPtr LoadLibrary(string librayName);

        //load library from \\SDK\lib\\
        static loadRogerLibrary()
        {
            string sdkDir =".";
            string libDir = "lib";
            string dllDirUsbHid = "RogerUSBHID";
            string dllDirRUD3 = "RogerRUD3";
            string dllDirMifare = "RogerMifare";

            try
            {
                // if wrong path try get from CurrentDirectory
                if (Directory.Exists(sdkDir) == false)
                {
                    Console.WriteLine("-------------------- 0");
                    //get default dir to SDK
                    string myPath = Environment.CurrentDirectory;
                    DirectoryInfo myDirectory;
                    do
                    {
                        myDirectory = Directory.GetParent(myPath);
                        myPath = myDirectory.ToString();
                        Console.WriteLine("-------------------- 0 " + myPath);

                    }
                    while (myDirectory.Name.Equals("SDK") == false);

                    sdkDir = myPath;
                    Console.WriteLine("-------------------- 0a " + myPath);
                }

                if (Directory.Exists(sdkDir))
                {
                    Console.WriteLine("-------------------- 1");
                    string setDllPath;

                    //RogerMifare lib path
                    setDllPath = Path.Combine(sdkDir, libDir, dllDirMifare, dllDirMifare + ".dll");
                    if (Path.HasExtension(setDllPath))
                        LoadLibrary(setDllPath);

                    //RogerUSBHID lib directory
                    setDllPath = Path.Combine(sdkDir, libDir, dllDirUsbHid, dllDirUsbHid + ".dll");
                    if (Path.HasExtension(setDllPath))
                        LoadLibrary(setDllPath);

                    //RogerRUD3 lib directory
                    setDllPath = Path.Combine(sdkDir, libDir, dllDirRUD3, dllDirRUD3 + ".dll");
                    if (Path.HasExtension(setDllPath))
                        LoadLibrary(setDllPath);
                }

            }
   
            catch (Exception exe)
            {
                InfoBuffer.error("---------Library load error\n" + exe.Message);

            }

        }

    }

}
