using System;
using System.Collections;
using static System.Configuration.ConfigurationSettings;
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using static iMESCore.Base.iMESConst;

namespace AutoLoaderLib_C
{


    static class modWIN
    {

        // ReviseDate : 2003/08/07,修改處理AdditionalXML
        // ReviseDate : 2003/08/05,新增Public gReturnArray
        // ReviseDate : 2003/07/01,更改AddFlow產生的Error(CInput)
        // ReviseDate : 2002/11/04,新增CUnInput function

        public static string gComputerName;
        public static string gReturnKeyValue;
        public static string gUserNo;
        public static string gUserName;
        public static string gUserLevel;
        public static string gLanguageMode;
        public static string gAppPath;
        // **Add for Smart Client Architecture
        public static string gMESWebServiceHost;
        public static string gCUSWebServiceHost;

        // Add By Peter 2005/6/20
        public static string gSettingMode = "";

        public static DataRow drSearch;

        public static ArrayList gReturnArray = new ArrayList();

        public const string strAddTagLabel = "extrabase";  // Add by py for Combine Addition XML doc
        public const string strAddTagName = "ExtraBase";    // Add by py for Combine Addition XML doc

        public static bool chkExecutionSuccess(ref System.Xml.XmlDocument Xmldoc)
        {
            bool chkExecutionSuccessRet = default(bool);
            if (Xmldoc.DocumentElement["result"].InnerXml == "success")
            {
                chkExecutionSuccessRet = true;
            }
            else
            {
                chkExecutionSuccessRet = false;
            }

            return chkExecutionSuccessRet;
        }

        public static string GetExceptionSysMsg(ref System.Xml.XmlDocument Xmldoc)
        {
            string GetExceptionSysMsgRet = default(string);
            string argstrInput = Xmldoc.DocumentElement.GetElementsByTagName("sysmsg").Item(0).InnerXml;
            GetExceptionSysMsgRet = CUnInput(ref argstrInput);
            Xmldoc.DocumentElement.GetElementsByTagName("sysmsg").Item(0).InnerXml = argstrInput;
            return GetExceptionSysMsgRet;
        }

        public static string GetExceptionMesMsg(ref System.Xml.XmlDocument Xmldoc)
        {
            string GetExceptionMesMsgRet = default(string);
            string argstrInput = Xmldoc.DocumentElement.GetElementsByTagName("mesmsg").Item(0).InnerXml;
            GetExceptionMesMsgRet = CUnInput(ref argstrInput);
            Xmldoc.DocumentElement.GetElementsByTagName("mesmsg").Item(0).InnerXml = argstrInput;
            return GetExceptionMesMsgRet;
        }

        public static string CombineXMLIdentity(ref string ComputerName, ref string CurUserNo, ref string SendTime)
        {
            string CombineXMLIdentityRet = default(string);
            CombineXMLIdentityRet = "<computername>" + ComputerName + "</computername>" + "<curuserno>" + CurUserNo + "</curuserno>" + "<sendtime>" + SendTime + "</sendtime>";

            return CombineXMLIdentityRet;
        }

        public static string CombineXMLParameter(ref string value_name, ref string name, ref string type, ref string value, ref string desc)
        {
            string CombineXMLParameterRet = default(string);
            CombineXMLParameterRet = "<" + value_name.ToLower() + ">" + "<name>" + name + "</name>" + "<type>" + type + "</type>" + "<value>" + value + "</value>" + "<desc>" + desc + "</desc>" + "</" + value_name.ToLower() + ">";




            return CombineXMLParameterRet;
        }

        public static string CombineXMLRequest(ref string strIdentity, ref string strParameter)
        {
            string CombineXMLRequestRet = default(string);
            CombineXMLRequestRet = "<request>" + "<identity>" + strIdentity + "</identity>";
            if (!string.IsNullOrEmpty(strParameter))
            {
                CombineXMLRequestRet = CombineXMLRequestRet + "<parameter>" + strParameter + "</parameter>";
            }
            CombineXMLRequestRet = CombineXMLRequestRet + "</request>";
            return CombineXMLRequestRet;
        }

        public static string CombineXMLValue(ref string TagName, ref string Value)
        {
            string CombineXMLValueRet = default(string);
            CombineXMLValueRet = "<" + TagName + ">" + Value + "</" + TagName + ">";
            return CombineXMLValueRet;
        }

        public static string CombineXMLValueTag(ref string Value)
        {
            string CombineXMLValueTagRet = default(string);
            CombineXMLValueTagRet = "<value>" + Value + "</value>";
            return CombineXMLValueTagRet;
        }

        public static string CombineXMLParameterMultiValue(ref string value_name, ref string name, ref string type, ref string value, ref string desc)
        {
            string CombineXMLParameterMultiValueRet = default(string);
            // Value不用加上Tag
            CombineXMLParameterMultiValueRet = "<" + value_name.ToLower() + ">" + "<name>" + name + "</name>" + "<type>" + type + "</type>" + value + "<desc>" + desc + "</desc>" + "</" + value_name.ToLower() + ">";



            return CombineXMLParameterMultiValueRet;
        }

        public static int FindRecordPosition(ref DataView dvData, ref string strColumnName, ref string strFindValue)
        {
            int FindRecordPositionRet = default(int);
            // //由Dataview的第一筆開始尋找符合的資料直到最後一筆
            // //傳出資料在資料表內的Index
            int i;
            bool Found;   // //紀錄是否找到符合資料
            string strDataType; // //尋找資料欄的資料型態

            try
            {
                if (!string.IsNullOrEmpty(strFindValue)) // 是否有傳入尋找的條件
                {
                    Found = false;
                    strDataType = dvData.Table.Columns[strColumnName].DataType.ToString();
                    if (strDataType == "System.DateTime") // 日期型態的資料比對
                    {
                        var loopTo = dvData.Count;
                        for (i = 0; i <= loopTo; i++)
                        {
                            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(dvData[i][strColumnName], "#" + Strings.Format(Conversions.ToDate(strFindValue), "yyyy/MM/dd") + "#", false)))
                            {
                                Found = true;
                                break;
                            }
                        }
                    }
                    else // 字串,數值資料型態的比對
                    {
                        var loopTo1 = dvData.Count;
                        for (i = 0; i <= loopTo1; i++)
                        {
                            if ((Strings.UCase(dvData[i][strColumnName].ToString()) ?? "") == (Strings.UCase(strFindValue) ?? ""))
                            {
                                Found = true;
                                break;
                            }
                        }
                    }
                    if (Found == true)
                    {
                        FindRecordPositionRet = i; // 找到符合資料，傳出所在的RowIndex 
                    }
                    else
                    {
                        FindRecordPositionRet = -1;
                    } // 沒有符合資料
                }
            }
            catch
            {
                FindRecordPositionRet = -1;
            } // 沒有符合資料

            return FindRecordPositionRet;

            // //使用Dataview的Find Method,日期無法使用
            // dvData.Sort = strColumnName
            // FindRecordPosition = dvData.Find(strFindValue)

        }


        public static string PasswordEncoding(ref string Password)
        {
            string PasswordEncodingRet = default(string);
            // 此 Function 將傳入值加以編碼後傳出,編碼後長度不變
            // 傳入值: 密碼
            // 傳回值: 編碼後密碼

            // Vernam密碼是由Gilbert Vernam在1918年發明的
            string g_Key = "xNDFz6LH67LOv7xKbWFpbMu1wejrM7SzvV4tLRvq3X47m708O1xMHLoaMNCqGhoaEN";
            string strChar, iCryptChar, strEncrypted = default(string);
            int i, iKeyChar, iStringChar;

            var loopTo = Strings.Len(Password);
            for (i = 1; i <= loopTo; i++)
            {
                iKeyChar = Strings.Asc(Strings.Mid(g_Key, i, 1));
                iStringChar = Strings.Asc(Strings.Mid(Password, i, 1));
                iCryptChar = (iKeyChar ^ iStringChar).ToString();
                strEncrypted = strEncrypted + Strings.Chr(Conversions.ToInteger(iCryptChar));
            }

            PasswordEncodingRet = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(strEncrypted));
            return PasswordEncodingRet;

        }

        public static string FilterByString(ref string strFilter, ref string strColumnName, ref string strColumnValue)
        {
            string FilterByStringRet = default(string);
            // 對字串欄位做篩選
            if (string.IsNullOrEmpty(strFilter))
            {
                strFilter = strColumnName + " = '" + Strings.Replace(strColumnValue, "'", "''") + "'";
            }
            else
            {
                strFilter = strFilter + " And " + strColumnName + " = '" + Strings.Replace(strColumnValue, "'", "''") + "'";
            }
            FilterByStringRet = strFilter;
            return FilterByStringRet;
        }


        public static string FilterByInteger(ref string strFilter, ref string strColumnName, ref int strColumnValue)
        {
            string FilterByIntegerRet = default(string);
            // 對數值欄位做篩選
            if (string.IsNullOrEmpty(strFilter))
            {
                strFilter = strColumnName + " = " + strColumnValue;
            }
            else
            {
                strFilter = strFilter + " And " + strColumnName + " = " + strColumnValue;
            }
            FilterByIntegerRet = strFilter;
            return FilterByIntegerRet;
        }

        public static string FilterByDate(ref string strFilter, ref string strColumnName, ref DateTime datFromDate, ref DateTime datEndDate)
        {
            string FilterByDateRet = default(string);
            // 對日期欄位做篩選
            if (string.IsNullOrEmpty(strFilter))
            {
                strFilter = strColumnName + " >= #" + Strings.Format(Conversions.ToDate(datFromDate), "yyyy/MM/dd 00:00:00") + "# And " + strColumnName + " <= #" + Strings.Format(Conversions.ToDate(datEndDate), "yyyy/MM/dd 23:59:59") + "# ";
            }
            else
            {
                strFilter = strFilter + " And " + strColumnName + " >= #" + Strings.Format(Conversions.ToDate(datFromDate), "yyyy/MM/dd 00:00:00") + "# And " + strColumnName + " <= #" + Strings.Format(Conversions.ToDate(datEndDate), "yyyy/MM/dd 23:59:59") + "# ";
            }
            FilterByDateRet = strFilter;
            return FilterByDateRet;
        }

        public static bool IsBoolean(ref string strBoolean, string strBooleanValue = defString)
        {
            bool IsBooleanRet = default(bool);
            // 此 Function 檢查傳入值是否為Boolean值
            // 傳入值: strBoolean欲檢查是否為Boolean值的字串
            // strBooleanValue將檢查值轉換為True或False的統一字串
            // 傳回值: True是Boolean值 ; False不是Boolean值

            IsBooleanRet = false;

            if (string.IsNullOrEmpty(strBoolean))
            {
                IsBooleanRet = false;
            }
            else if (Strings.Trim(Strings.UCase(strBoolean)) != "Y" & Strings.Trim(Strings.UCase(strBoolean)) != "N" & Strings.Trim(Strings.UCase(strBoolean)) != "T" & Strings.Trim(Strings.UCase(strBoolean)) != "F" & Strings.Trim(Strings.UCase(strBoolean)) != "YES" & Strings.Trim(Strings.UCase(strBoolean)) != "NO" & Strings.Trim(Strings.UCase(strBoolean)) != "TRUE" & Strings.Trim(Strings.UCase(strBoolean)) != "FALSE" & Strings.Trim(Strings.UCase(strBoolean)) != "是" & Strings.Trim(Strings.UCase(strBoolean)) != "否" & Strings.Trim(Strings.UCase(strBoolean)) != "ON" & Strings.Trim(Strings.UCase(strBoolean)) != "OFF")




            {

                IsBooleanRet = false;
            }

            else if (Strings.Trim(Strings.UCase(strBoolean)) == "Y" | Strings.Trim(Strings.UCase(strBoolean)) == "T" | Strings.Trim(Strings.UCase(strBoolean)) == "YES" | Strings.Trim(Strings.UCase(strBoolean)) == "TRUE" | Strings.Trim(Strings.UCase(strBoolean)) == "是" | Strings.Trim(Strings.UCase(strBoolean)) == "ON")

            {
                IsBooleanRet = true;
                strBooleanValue = "True";
            }
            else
            {
                IsBooleanRet = true;
                strBooleanValue = "False";
            }

            return IsBooleanRet;
        }


        public static string CInput(ref string strInput)
        {
            string CInputRet = default(string);
            // 將傳入值內的單引號轉換為可存入資料庫的格式
            // 2. 將傳入值內的 &, >, < 三個特殊字元轉換為XmlDocument可解譯之代替符號                  
            // 傳入值: strInput包含特殊字元的字串
            // 傳回值: 將特殊字元變更為代替符號的字串

            // 轉換 ' 為 '' (單引號轉為兩個單引號)
            CInputRet = Strings.Replace(strInput, "'", "''");

            // 轉換 & 為 &amp;
            CInputRet = Strings.Replace(CInputRet, "&", "&amp;");

            // CInput = Replace(CInput, """", "''")   'AddFlow的Xml字串不可將雙引號轉為兩個單引號,XMLToFlow會Error

            // 轉換 > 為 &gt;
            CInputRet = Strings.Replace(CInputRet, ">", "&gt;");

            // 轉換 < 為 &lt;
            CInputRet = Strings.Replace(CInputRet, "<", "&lt;");
            return CInputRet;

        }

        public static string CUnInput(ref string strInput)
        {
            string CUnInputRet = default(string);
            // 將傳入值內的單引號轉換為可存入資料庫的格式
            // 傳入值: strInput包含特殊字元的字串
            // 傳回值: 將代替符號變更為特殊字元的字串

            // 轉換 ' 為 '' (單引號轉為兩個單引號)
            // CUnInput = Replace(strInput, "'", "''")
            CUnInputRet = Strings.Replace(strInput, "\"", "'");

            // 轉換 & 為 &amp;
            CUnInputRet = Strings.Replace(CUnInputRet, "&amp;", "&");

            // 轉換 > 為 &gt;
            CUnInputRet = Strings.Replace(CUnInputRet, "&gt;", ">");

            // 轉換 < 為 &lt;
            CUnInputRet = Strings.Replace(CUnInputRet, "&lt;", "<");
            return CUnInputRet;

        }


        // ***Add by PY 2003/07/31****
        public static string CombineXMLAdditional(ref string strAdditional)
        {
            string CombineXMLAdditionalRet = default(string);
            CombineXMLAdditionalRet = "<additional>" + strAdditional;
            CombineXMLAdditionalRet = CombineXMLAdditionalRet + "</additional>";
            return CombineXMLAdditionalRet;
        }

        public static string CombineAddXML_Add(ref string name, ref string type, ref string value)
        {
            string CombineAddXML_AddRet = default(string);
            CombineAddXML_AddRet = "<field>" + "<name>" + name + "</name>" + "<type>" + type + "</type>" + "<value>" + value + "</value>" + "</field>";



            return CombineAddXML_AddRet;
        }
        public static string CombineAddXML_Edit(ref string name, ref string type, ref string value)
        {
            string CombineAddXML_EditRet = default(string);
            CombineAddXML_EditRet = "<field>" + "<name>" + name + "</name>" + "<type>" + type + "</type>" + "<value>" + value + "</value>" + "</field>";



            return CombineAddXML_EditRet;
        }
        public static string CombineAddXML_Field(ref string name)
        {
            string CombineAddXML_FieldRet = default(string);
            CombineAddXML_FieldRet = "<field>" + "<name>" + name + "</name>" + "</field>";

            return CombineAddXML_FieldRet;
        }

        public static string CombineAddXML_Condition(string condition)
        {
            string CombineAddXML_ConditionRet = default(string);
            CombineAddXML_ConditionRet = "<condition>" + Strings.Replace(condition, "''", "'") + "</condition>";
            return CombineAddXML_ConditionRet;
        }

        // **Add by py 2003/12/04,Gary Lu 20120911:以MESWin1~Win4的版本進行替換
        public static string LocalizeWebService(string wsUrl, bool Customize = false)
        {

            string[] tmpString;
            int i;
            tmpString = wsUrl.Split('/');
            if (Customize == true)
            {
                if (!string.IsNullOrEmpty(Strings.Trim(gCUSWebServiceHost)))
                {
                    if (tmpString.Length == 6)
                    {
                        wsUrl = tmpString[0].ToString() + "/" + tmpString[1].ToString() + "/" + gCUSWebServiceHost + "/" + tmpString[4].ToString() + "/" + tmpString[5].ToString();
                    }
                    else if (tmpString.Length == 5)
                    {
                        wsUrl = "http://" + gCUSWebServiceHost + "/" + tmpString[tmpString.Length - 1].ToString();
                    }
                }
            }
            else if (!string.IsNullOrEmpty(Strings.Trim(gMESWebServiceHost)))
            {
                if (tmpString.Length == 6)
                {
                    // wsUrl = "http://" & gMESWebServiceHost & "/" & tmpString(tmpString.Length - 2).ToString & "/" & tmpString(tmpString.Length - 1).ToString
                    wsUrl = tmpString[0].ToString() + "/" + tmpString[1].ToString() + "/" + gMESWebServiceHost + "/" + tmpString[4].ToString() + "/" + tmpString[5].ToString();
                }
                else if (tmpString.Length == 5)
                {
                    // wsUrl = "http://" & gMESWebServiceHost & "/" & tmpString(tmpString.Length - 1).ToString
                    wsUrl = tmpString[0].ToString() + "/" + tmpString[1].ToString() + "/" + gMESWebServiceHost + "/" + tmpString[4].ToString();
                }
            }

            return wsUrl;
            // Have to assume the web service is on the machine that this application came from
        } // LocalizeWebService

        // Add By Peter 2005/6/20
        public static string GetAppSettings(string key, string section = "")
        {
            string result = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(section))
                {
                    result = Conversions.ToString(((Hashtable)GetConfig(section))[key]);
                }
                else if (string.IsNullOrEmpty(gSettingMode) || string.IsNullOrEmpty(gSettingMode) || gSettingMode.Length == 0)
                {
                    result = AppSettings[key];
                }
                else
                {
                    Hashtable ht = (Hashtable)GetConfig(gSettingMode);
                    if (ht != null)
                    {
                        result = Conversions.ToString(ht[key]);
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }


        public static string GetExceptionStack(ref System.Xml.XmlDocument Xmldoc)
        {
            string GetExceptionStackRet = default(string);
            if (Xmldoc.DocumentElement.GetElementsByTagName("stack").Count > 0)
            {
                string argstrInput = Xmldoc.DocumentElement.GetElementsByTagName("stack").Item(0).InnerXml;
                GetExceptionStackRet = CUnInput(ref argstrInput);
                Xmldoc.DocumentElement.GetElementsByTagName("stack").Item(0).InnerXml = argstrInput;
            }
            else
            {
                GetExceptionStackRet = "";
            }

            return GetExceptionStackRet;
        }

    }
}