using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using Microsoft.VisualBasic.FileIO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using iMESCore.Settings;
using static iMESCore.DataBase.iMESSql;
using static iMESCore.Base.iMESConst;
using System.Data.Common;

namespace AutoLoaderLib_C
{

    public class clsAutoLoaderLibrary
    {

        //private System.Data.OleDb.OleDbCommand cmmTemp;
        private string strConnectionString;             // Connection string
        private string strReportConnectionString;       // Report DB Connection string
        private string strDataBaseType;                 // DataBase Type:oracle, mysql, access
        private string strMQType;                       // MessageQueue Type:TIBCO, MQSeries, MSMQ

        private AppSettings objSetting = new AppSettings();

        private string InXml, OutXml, strIdentity, strParameter, XmlData, XmlSchema;

        // //Initial Object--------------------------------------------------------------------------------------------------------------------------------
        public clsAutoLoaderLibrary()
        {
            // //Get database type
            strDataBaseType = objSetting.GetDataBaseType();
            // //Get connection string
            strConnectionString = objSetting.GetConnectionString(strDataBaseType);
            // //Get Message Queue Type
            strMQType = objSetting.GetMQType();
            // //Get connection string    
            strReportConnectionString = objSetting.GetReportConnectionString(strDataBaseType);
            // //GetMESWebSer
            modWIN.gMESWebServiceHost = objSetting["MESWebServiceHost"].ToString();
        }

        // //Property--------------------------------------------------------------------------------------------------------------------------------
        public string ConnectionString
        {
            get
            {
                return strConnectionString;
            }
        }

        public string DataBaseType
        {
            get
            {
                return strDataBaseType;
            }
        }

        public string MQType
        {
            get
            {
                return strMQType;
            }
        }

        // //Public function----------------------------------------------------------------------------------------------------
        public string ExecuteFunction(string FunctionName, Collection colParameters = null)
        {
            string ExecuteFunctionRet = default(string);
            // 此 Function 將執行傳入之FunctionName
            // 傳入值: FunctionName,colParameters
            // 傳回值: DataSet(成功), nothing(失敗)

            // colParameters的資料範例如下
            // colParameters.Add("C1", "CustomerNo")
            // colParameters.Add("P1", "ProductNo")

            int i;

            try
            {

                // 1.處理 FunctionName 大小寫問題
                System.Reflection.MethodInfo[] MyMethodInfos = GetType().GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); // 取出Private的Function
                var loopTo = MyMethodInfos.Length - 1;
                for (i = 0; i <= loopTo; i++)
                {
                    if ((MyMethodInfos[i].Name.ToUpper() ?? "") == (FunctionName.ToUpper() ?? ""))
                    {
                        FunctionName = MyMethodInfos[i].Name;
                        break;
                    }
                }

                // 2.執行Private Function,傳出DataSet
                object objArgs = new object[] { colParameters };
                ExecuteFunctionRet = Conversions.ToString(GetType().InvokeMember(FunctionName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, this, (object[])objArgs));
            }

            catch (Exception e1)
            {
                ExecuteFunctionRet = "fail";
                throw new Exception("clsAutoLoaderLibrary.ExecuteFunction:" + "{" + FunctionName + "}" + e1.Message);
            }

            finally
            {

            }

            return ExecuteFunctionRet;

        }

        #region ---AutoLoader function---


        #endregion

        #region ---AutoLoader Sample---

        private string funWatchTest(Collection colParameters = null)
        {
            string funWatchTestRet = default(string);

            string strJobNo = string.Empty;                   // JobNo
            string strSourcePath = string.Empty;              // 來源檔案路徑
            string strDestinationPath = string.Empty;         // 目前檔案路徑
            string strQueuePath = string.Empty;               // 處理中檔案路徑
            string strFailPath = string.Empty;                // 失敗檔案路徑
            string FileName = string.Empty;                   // 處理中檔案
            string DirName = DateTime.Now.ToString("yyyyMM");          // 分類目錄名稱
            string strLotNo = string.Empty;
            string strComponentNo = string.Empty;
            bool blnMoveFile = true;
            string strSQL = string.Empty;

            try
            {
                // //取出colParameter傳入參數
                strJobNo = colParameters["JobNo"].ToString().Trim();
                strSourcePath = colParameters["SourcePath"].ToString().Trim();
                strDestinationPath = colParameters["DestinationPath"].ToString().Trim();
                strQueuePath = colParameters["QueuePath"].ToString().Trim();
                strFailPath = colParameters["FailPath"].ToString().Trim();
                // //取出來源目錄中*.csv檔案
                string[] DirFiles = Directory.GetFiles(strSourcePath, "*.csv");
                // //將檔案複製到Queue的目錄中
                foreach (var currentFileName in DirFiles)
                {
                    FileName = currentFileName;
                    // //檢查檔案存不存在，有可能被另一個執行緒先處理
                    if (File.Exists(FileName) == true)
                    {
                        // '//檔案已存在Queue必須先刪除
                        // If File.Exists(strQueuePath & Path.GetFileName(FileName)) = True Then
                        // File.Delete(strQueuePath & Path.GetFileName(FileName))
                        // End If
                        // //移動檔案Source至Queue
                        try
                        {
                            blnMoveFile = true;
                            File.Move(FileName, strQueuePath + Path.GetFileName(FileName));
                        }
                        catch (Exception ex)
                        {
                            blnMoveFile = false;
                            throw new Exception("此執行程序已中止，由另一執行程序處理中!!");
                        }
                        // //將檔案來源改為Queue
                        FileName = strQueuePath + Path.GetFileName(FileName);
                        // //開始執行解檔處理
                        using (var myReader = new TextFieldParser(FileName, Encoding.Default))
                        {
                            myReader.TextFieldType = FieldType.Delimited;
                            myReader.Delimiters = new string[] { "," };
                            // //建立Connection
                            var cnnTemp = CreateConnection(strConnectionString);
                            //System.Data.OleDb.OleDbCommand cmmTemp = null;
                            //System.Data.OleDb.OleDbDataAdapter daTemp = null;
                            DbDataReader drTemp = null;
                            var CollectionSQL = new Collection();
                            // //變數宣告區域

                            // //Try Catch
                            try
                            {
                                // //Parser檔案 
                                while (!myReader.EndOfData)
                                {

                                }

                                // //執行SQL
                                ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL);
                            }

                            catch (Exception ex)
                            {
                                throw;
                            } // //直接將錯誤Throw出去

                            finally
                            {
                                // //釋放資源
                                CollectionSQL = null;
                                // //Close Connection
                                CloseConnection(cnnTemp);
                            }
                        }
                        // //目錄不存在時必須要先建立
                        if (Directory.Exists(strDestinationPath + DirName) == false)
                        {
                            Directory.CreateDirectory(strDestinationPath + DirName);
                        }
                        // //檔案已存在Destination必須先刪除
                        if (File.Exists(strDestinationPath + DirName + @"\" + Path.GetFileName(FileName)) == true)
                        {
                            File.Delete(strDestinationPath + DirName + @"\" + Path.GetFileName(FileName));
                        }
                        // //移動檔案Queue至Destination
                        File.Move(FileName, strDestinationPath + DirName + @"\" + Path.GetFileName(FileName));
                    }
                }
                // //回傳Success
                funWatchTestRet = "success";
            }

            catch (Exception ex)
            {
                // //檔案處理失敗時移動檔案Queue至Fail
                if (!string.IsNullOrEmpty(FileName) && blnMoveFile == true)
                {
                    // //目錄不存在時必須要先建立
                    if (Directory.Exists(strFailPath + DirName) == false)
                    {
                        Directory.CreateDirectory(strFailPath + DirName);
                    }
                    // //檔案已存在File必須先刪除
                    if (File.Exists(strFailPath + DirName + @"\" + Path.GetFileName(FileName)) == true)
                    {
                        File.Delete(strFailPath + DirName + @"\" + Path.GetFileName(FileName));
                    }
                    // //移動檔案Queue至Fail
                    try
                    {
                        File.Move(FileName, strFailPath + DirName + @"\" + Path.GetFileName(FileName));
                    }
                    catch (Exception ex1)
                    {
                    }

                }
                // //回傳錯誤原因
                funWatchTestRet = CombineFailMsg("0000-999999", "[JobNo:" + strJobNo + "][FunctionNo:funWatchTest][FileName:" + FileName + "][LotNo:" + strLotNo + "][WaferNo:" + strComponentNo + "][" + ex.Message + ",StackTrace:" + ex.StackTrace + "][SQL:" + strSQL + "]");
            }
            finally
            {


            }

            return funWatchTestRet;

        }

        #endregion

        #region ---Error Log---

        // //Function--------------------------------------------------------------------------------------------------------------------------------- 
        public string AddErrorLog(string ServiceName, string UserID, string KeyField, string KeyValue, DateTime RecordDate = default(DateTime), string Description = defString, string ComputerName = defString)



        {
            string AddErrorLogRet = default(string);
            // 此 Function 將新增一筆資料
            // 傳入值: 各欄位新增值
            // 傳回值: success(成功), fail(失敗)

            string strSQLAddField = string.Empty;
            string strSQLAddValue = string.Empty;
            string strSQL = string.Empty;

            if (RecordDate == defDateTime)
                RecordDate = DateTime.Now;

            try
            {
                strSQLAddField = "Insert into tblSysErrorLog (ServiceName, UserID, KeyField, KeyValue";
                strSQLAddValue = " Values ('" + ChkSingleQuation(Strings.Left(ServiceName, 30)) + "','" + ChkSingleQuation(Strings.Left(UserID, 10)) + "','" + ChkSingleQuation(Strings.Left(KeyField, 999)) + "','" + ChkSingleQuation(Strings.Left(KeyValue, 999)) + "'";

                if ((Description ?? "") != defString)
                {
                    strSQLAddField += ",Description";
                    strSQLAddValue += ",'" + ChkSingleQuation(Strings.Left(Description, 1999)) + "'";
                }
                if (RecordDate != defDateTime)
                {
                    strSQLAddField += ",RecordDate";
                    strSQLAddValue += ", To_Date('" + Strings.Format(Conversions.ToDate(RecordDate), "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')";
                }
                if ((ComputerName ?? "") != defString)
                {
                    strSQLAddField += ",ComputerName";
                    strSQLAddValue += ",'" + ChkSingleQuation(Strings.Left(ComputerName, 50)) + "'";
                }

                // 直接給定strSQL
                strSQL = strSQLAddField + ")" + strSQLAddValue + ")";

                // //執行SQL指令
                string argstrDatabaseType = Conversions.ToString(DataBaseType);
                ExecuteSQLNoneQuery(argstrDatabaseType, strConnectionString, ref strSQL);

                // //Return success
                AddErrorLogRet = "success";
            }

            catch (Exception e1)
            {
                AddErrorLogRet = "fail";
                // 發生錯誤時丟回本身的Function Name及系統錯誤訊息
                // Throw 'New Exception("kcSYS.AddErrorLog: " & e1.Message)

            }

            return AddErrorLogRet;

        }
        private string CombineFailMsg(string ErrorCode, string Desc)
        {
            string CombineFailMsgRet = default(string);
            CombineFailMsgRet = "ErrorCode:" + ErrorCode + ";" + Desc;
            return CombineFailMsgRet;
        }
        #endregion

        ~clsAutoLoaderLibrary()
        {
            if (objSetting != null)
                objSetting = null;
        }

    }
}