using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
using System.Data.SqlClient;

using DataBaseConnection.Control;

using DevExpress.XtraBars;

using SystemX.Common;
using SystemX.Product.ALIS.Interface;
using SystemX.Product.ALIS.UI.View.Base;
using SystemX.Product.ALIS.UI.View;
using SystemX.Net.Platform.Common.Util;
using SystemX.Product.ALIS.UI.Subs;

using static SystemX.Product.ALIS.UI.View.ViewCfg;
using static SystemX.Net.Platform.Common.Util.LogMessage;


namespace SystemX.Product.ALIS.UI
{
    public partial class FrmMain
    {
        /// <summary>
        /// IDataController
        /// </summary>
        object objSQLControl = new object();

        /// <summary>
        /// IDataController - GetConnSqlCmd
        /// </summary>
        /// <returns></returns>
        public SqlCommand GetConnSqlCmd()
        {
            return SQLCmd;
        }

        /// <summary>
        /// IDataController - GetDuplicateCheck
        /// </summary>
        /// <param name="strTableName"></param>
        /// <param name="strFieldName"></param>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public bool GetDuplicateCheck(string strTableName, string strFieldName, string strValue)
        {
            SqlDataReader dr = null;
            bool bHasRows = true;

            try
            {
                SQLCmd.CommandText = "SELECT * FROM[" + strTableName + "] WHERE No IN(SELECT No FROM[" + strTableName + "] WHERE " + strFieldName + " = '" + strValue + "') ORDER BY No ASC;";

                dr = SQLCmd.ExecuteReader();

                if (dr != null)
                    bHasRows = dr.HasRows;
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>> ") + @"Query process fail. [SystemX.Product.ALIS.UI : IDataController.GetDuplicateCheck]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }

            return bHasRows;
        }

        /// <summary>
        /// IDataController - GetLoginInfo
        /// </summary>
        /// <returns></returns>
        public UserInfo GetLoginInfo()
        {
            return CurrentUser;
        }

        private DataTable QuerySQL(string strQueryText)
        {
            lock (objSQLControl)
            {
                SqlDataReader sqlReader = null;
                DataTable dt = new DataTable();

                try
                {
                    SQLCmd.CommandText = strQueryText;
                    sqlReader = SQLCmd.ExecuteReader();

                    if (sqlReader.HasRows != false)
                        dt.Load(sqlReader);
                }
                catch (Exception ex)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>> ") + @"Query process fail. [SystemX.Product.ALIS.UI : IDataController.QuerySQL]\r\n" + ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }
                finally
                {
                    if (sqlReader != null)
                        sqlReader.Close();
                }

                if (XCommons.isHasRow(dt))
                    return dt;
                else
                    return null;
            }
        }

        public DataTable GetTable(string strQueryText)
        {
            return QuerySQL(strQueryText);
        }

        /// <summary>
        /// IDataController - GetTable
        /// </summary>
        /// <param name="tblName"></param>
        /// <returns></returns>
        public DataTable GetTable(eDbTableList tblName)
        {
            string strQueryText = string.Empty;
            
            strQueryText = $"SELECT * FROM {tblName.ToString()} WITH(NOLOCK) ORDER BY No ASC;";

            if (tblName == eDbTableList.STOR_TestListFile)
            {
                strQueryText = $"SELECT X.No, " +
                    $"X.Name, " +
                    $"X.FileName, " +
                    $"X.TestType, " +
                    $"X.Version AS 'FileVersion', " +
                    $"X.ProdCode, " +
                    $"X.RegDT, " +
                    $"X.RegUser, " +
                    $"X.UpdateDT, " +
                    $"X.UpdateUser, " +
                    $"X.Comment, " +
                    $"X.Description, " +
                    $"Z.LatestStepVersion AS 'Step Version' " +
                    $"FROM [{tblName.ToString()}] AS X WITH(NOLOCK) " +
                    $"LEFT JOIN [HIST_TestListFileLatestStepVersion] AS Z WITH(NOLOCK) ON Z.TestListFileNo = X.No " +
                    $"ORDER BY No ASC;";
            }
            else if (tblName == eDbTableList.PROD_Variant)
            {
                strQueryText = $"SELECT X.No, " +
                    $"X.ProdNo_P AS 'P_ProdNo', " +     
                    $"I.TestType, " +
                    $"I.FileName, " +
                    $"I.Version AS 'FileVersion', " +
                    $"I.ProdCode, " +
                    $"I.No AS 'TestListFileNo', " +
                    $"I.Name AS 'TestListName', " +
                    $"X.RegDT, " +
                    $"X.RegUser, " + 
                    $"X.UpdateDT, " +
                    $"X.UpdateUser, " +
                    $"Y.No AS 'GroupNo', " +
                    $"Y.GroupName, " +
                    $"Y.ModelName, " +
                    //$"Y.Comment AS 'Model-Comment', " +
                    $"X.Comment, " +
                    $"I.Description, " +
                    $"X.UseTLPosition AS 'Test-List Position', " +
                    $"Z.LatestStepVersion AS 'Step Version' " +
                    //$"X.TestListData " +
                    $"FROM {tblName.ToString()} AS X WITH(NOLOCK) " +
                    $"LEFT JOIN [PROD_Group] AS Y WITH(NOLOCK) ON X.GroupNo = Y.No " +
                    $"LEFT JOIN [STOR_TestListFile] AS I WITH(NOLOCK) ON X.TestListFileNo = I.No " +
                    $"LEFT JOIN [HIST_TestListFileLatestStepVersion] AS Z WITH(NOLOCK) ON X.TestListFileNo = Z.TestListFileNo " +
                    $"ORDER BY No ASC;";
            }
            else if (tblName == eDbTableList.PROD_Release)
            {
                strQueryText = $"SELECT X.No, " +
                    $"K.ModelName, " +
                    $"X.ProdNo_C AS 'C_ProdNo', " +
                    $"Y.No AS 'TestCodeNo', " +
                    $"Y.TestCode, " +
                    $"Z.No AS 'VariantNo', " +
                    $"Z.ProdNo_P AS 'P_ProdNo', " +
                    $"J.TestType, " +
                    $"J.Version AS 'FileVersion', " +
                    $"J.ProdCode, " +
                    $"X.Config, " +
                    $"X.RegDT, " +
                    $"X.RegUser, " +
                    $"X.RegUserComment " +
                    $"FROM {tblName.ToString()} AS X WITH(NOLOCK) " +
                    $"LEFT JOIN [STAT_TestCode] AS Y WITH(NOLOCK) ON X.TestCodeNo = Y.No " +
                    $"LEFT JOIN [PROD_Variant] AS Z WITH(NOLOCK) ON X.VariantNo = Z.No " +
                    $"LEFT JOIN [PROD_Group] AS K WITH(NOLOCK) ON K.No = Z.GroupNo " +
                    $"LEFT JOIN [STOR_TestListFile] AS J WITH(NOLOCK) ON Z.TestListFileNo = J.No " +
                    $"OR X.No IS NULL ORDER BY No ASC;"; 
            }

            return QuerySQL(strQueryText);
        }

        /// <summary>
        /// IDataController - GetTable
        /// </summary>
        /// <param name="tblName"></param>
        /// <param name="strColName"></param>
        /// <param name="strParameter"></param>
        /// <returns></returns>
        public DataTable GetTable(eDbTableList tblName, string strColName, string strParameter)
        {
            string strQueryText = $"SELECT * FROM {tblName.ToString()} WITH(NOLOCK) WHERE {strColName} = {strParameter} ORDER BY No ASC;";

            return QuerySQL(strQueryText);
        }

        /// <summary>
        /// IDataController - GetServerDateTimeString
        /// </summary>
        /// <returns></returns>
        public string GetServerDateTimeString()
        {
            string strGetDateTime = string.Empty;

            string strQueryText = "SELECT CONVERT(datetime2, GETDATE(), 121) AS CURRENT_DATETIME;";

            DataTable getDt =  QuerySQL(strQueryText);

            if (XCommons.isHasRow(getDt))
                strGetDateTime = getDt.Rows[0].ItemArray[0].ToString();

            return strGetDateTime;
        }

        /// <summary>
        /// IDataController - GetServerDateTime
        /// </summary>
        /// <returns></returns>
        public DateTime GetServerDateTime()
        {
            string strGetDateTime = string.Empty;

            string strQueryText = "SELECT CONVERT(datetime2, GETDATE(), 121) AS CURRENT_DATETIME;";

            DataTable getDt = QuerySQL(strQueryText);

            if (XCommons.isHasRow(getDt))
                strGetDateTime = getDt.Rows[0].ItemArray[0].ToString();

            DateTime dtSetDateTime = new DateTime();
            DateTime.TryParse(strGetDateTime, out dtSetDateTime);

            return dtSetDateTime;
        }

        /// <summary>
        /// IDataController - SetConvertDateTime
        /// </summary>
        /// <param name="strGetConvertText"></param>
        /// <returns></returns>
        public string SetConvertDateTime(string strGetConvertText)
        {
            string strQueryConvertText = string.Empty;

            if (strGetConvertText.IndexOf("AM") >= 0 || strGetConvertText.IndexOf("PM") >= 0 ||
               strGetConvertText.IndexOf("오전") >= 0 || strGetConvertText.IndexOf("오후") >= 0)
            {
                if (strGetConvertText.IndexOf("AM") >= 0 || strGetConvertText.IndexOf("PM") >= 0)
                    strQueryConvertText = "SELECT dbo.XConvertDateE('" + strGetConvertText + "') AS CONVERT_DATETIME_E;";
                else if (strGetConvertText.IndexOf("오전") >= 0 || strGetConvertText.IndexOf("오후") >= 0)
                    strQueryConvertText = "SELECT dbo.XConvertDateK('" + strGetConvertText + "') AS CONVERT_DATETIME_K;";
            }

            DataTable getDt = null;

            string strGetResultText1 = string.Empty;
            string strGetResultText2 = string.Empty;

            if (strQueryConvertText != string.Empty)
                getDt = QuerySQL(strQueryConvertText);
            else
                strGetResultText1 = strGetConvertText;

            if (XCommons.isHasRow(getDt))
                strGetResultText1 = getDt.Rows[0].ItemArray[0].ToString();

            string strQueryText = "SELECT CONVERT(VARCHAR, '" + strGetResultText1 + "', 121) AS CONVERT_DATETIME;";

            if (strGetResultText1 != string.Empty)
                getDt = QuerySQL(strQueryText);
            
            if (XCommons.isHasRow(getDt))
                strGetResultText2 = getDt.Rows[0].ItemArray[0].ToString();

            return strGetResultText2;
        }
    }
}