using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using iMESCIO.PIO.Plugin;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

namespace MESPI_BusinessRule
{

    public class clsGetFunctionBR : ICommonPlugin
    {

        public string PlugInPoint
        {
            get
            {
                return "wsOP.LoadBRFunctionName";
            }
        }

        public object AfterExecut(params object[] Parameters)
        {

            string strAppBase = AppDomain.CurrentDomain.BaseDirectory;
            string strFilePath = strAppBase.TrimEnd('\\') + @"\Plugin\BusinessRule";
            Assembly mainAssembly;
            MethodInfo[] MyMethodInfos;
            string strFunction;
            string strResult = "";

            try
            {

                foreach (string file in Directory.GetFiles(strFilePath))
                {

                    if (new System.IO.FileInfo(file).Extension.ToUpper() != ".DLL")
                    {
                        continue;
                    }

                    mainAssembly = Assembly.LoadFrom(file);

                    foreach (Type item in mainAssembly.GetTypes())
                    {

                        var InterfaceTemp = item.GetInterfaces().Where(x => (x.Name ?? "") == (typeof(IBusinessRule).Name.ToString() ?? "")).FirstOrDefault();

                        if (InterfaceTemp == null == false)
                        {

                            MyMethodInfos = item.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);

                            for (int i = 0, loopTo = MyMethodInfos.Length - 1; i <= loopTo; i++)
                            {

                                strFunction = MyMethodInfos[i].Name;

                                if (Conversions.ToBoolean(Strings.InStr(strFunction.ToUpper(), "FUNBR")))
                                {
                                    strResult += "<functionname>" + "<name>FunctionName</name>" + "<type>String</type>" + "<schema></schema>" + "<value>" + strFunction + "</value>" + "<desc></desc>" + "<filename>" + new System.IO.FileInfo(file).Name + "</filename>" + "</functionname>";
                                }

                            }

                        }

                    }

                }
            }

            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                mainAssembly = null;
                MyMethodInfos = null;
            }

            return strResult;

        }

        public object BeforeExecut(ref bool paramIsCancel, params object[] Parameters)
        {
            throw new NotImplementedException();
        }

    }
}