using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemX.Net.XAdaptor.PC;
using SystemX.Net.Platform.Common.ExtensionMethods;
using static SystemX.Net.XAdaptor.PC.O2Sensor.NgCode.DBSchemaMap;
using static SystemX.Net.Platform.Common.Util.LogMessage;

namespace SystemX.Net.XAdaptor.PC.O2Sensor.NgCode
{
	public class NGHistDBFinder
	{
		string SET_NG_HIST_TABLE_NAME = "HIST_TestNgResult";
		//Name - ProcNo - TestID
		Dictionary<eHistProcTableList, Tuple<int, string>> dicHistInfo;

		XAdaptorPC refPCAdaptor;

		public NGHistDBFinder(XAdaptorPC refAdaptor)
		{
			refPCAdaptor = refAdaptor;

			dicHistInfo = new Dictionary<eHistProcTableList, Tuple<int, string>>();
			dicHistInfo.Add(eHistProcTableList.HIST_ProdLoad, new Tuple<int, string>(180, "PL"));
			dicHistInfo.Add(eHistProcTableList.HIST_CapDeassy, new Tuple<int, string>(180, "CDA"));
			dicHistInfo.Add(eHistProcTableList.HIST_PreHeating, new Tuple<int, string>(190, "PH"));
			dicHistInfo.Add(eHistProcTableList.HIST_PreMeas, new Tuple<int, string>(190, "PM"));
			dicHistInfo.Add(eHistProcTableList.HIST_Leak, new Tuple<int, string>(200, "LK"));
			dicHistInfo.Add(eHistProcTableList.HIST_LaserTrim, new Tuple<int, string>(210, "LT"));
			dicHistInfo.Add(eHistProcTableList.HIST_LaserTrimVision, new Tuple<int, string>(220, "LTV"));
			dicHistInfo.Add(eHistProcTableList.HIST_IsoRes, new Tuple<int, string>(220, "IR"));
			dicHistInfo.Add(eHistProcTableList.HIST_CapAssy, new Tuple<int, string>(230, "CA"));
			dicHistInfo.Add(eHistProcTableList.HIST_Function, new Tuple<int, string>(240, "FT"));
			dicHistInfo.Add(eHistProcTableList.HIST_OutSealPress, new Tuple<int, string>(250, "OSP"));
			dicHistInfo.Add(eHistProcTableList.HIST_PinVision, new Tuple<int, string>(260, "PV"));
			dicHistInfo.Add(eHistProcTableList.HIST_PinLVDT, new Tuple<int, string>(260, "LVDT"));
		}

		public Dictionary<eHistProcTableList, DataRow> FindHistory(string strMESID, string strPalletID, bool bFristFailScan = false)
		{
			Dictionary<eHistProcTableList, DataRow> dicResult = new Dictionary<eHistProcTableList, DataRow>();

			string strQuery = $"SELECT * FROM {SET_NG_HIST_TABLE_NAME.ToString()} WHERE No IN (SELECT No FROM {SET_NG_HIST_TABLE_NAME.ToString()} WHERE " +
			$"{eHistTableCommonCols.ProdID} = '{strMESID}' AND {eHistTableCommonCols.PalletID} = '{strPalletID}') " +
			$"ORDER BY {eHistTableCommonCols.ProcNo.ToString()};";

			DataSet dsResult = null;

			try
			{
				dsResult = refPCAdaptor.WaitSystemQuery(strQuery);
				DataRow dr = null;

				foreach (eHistProcTableList tableName in Enum.GetValues(typeof(eHistProcTableList)))
				{
					int iProcNo = dicHistInfo[tableName].Item1;
					string strTestID = dicHistInfo[tableName].Item2;

					bool bNgRowFind = false;
					dr = null;

					foreach (var item in dsResult.Tables[0].Rows)
					{
						dr = item as DataRow;

						int iIndex = dsResult.Tables[0].Rows.IndexOf(dr);

						string strGetProcNo = dsResult.Tables[0].Rows[iIndex][eHistTableCommonCols.ProcNo.ToString()].ToString().Trim();
						string strGetTestID = dsResult.Tables[0].Rows[iIndex][eHistTableCommonCols.TestID.ToString()].ToString().Trim();

						if (strGetProcNo == iProcNo.ToString() &&
						strGetTestID == strTestID)
						{
							bNgRowFind = true;

							break;
						}
					}

					if (bNgRowFind)
					{
						dicResult.Add(tableName, dr);

						//이력 존재시 NG
						if (bFristFailScan)
							break;
					}
					else
					{
						dicResult.Add(tableName, null);

						//이력 미 존재시 PASS
					}
				}
			}
			catch (Exception ex)
			{
				MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
				   @"NgCode<Exception> - NGHistDBFinder - FindHistory()\r\n" +
				   ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
			}
			finally { }

			return dicResult;
		}
		public Tuple<eHistProcTableList, DataRow, bool> FindNGHistory(string strMESID, string strPalletID)
		{
			Tuple<eHistProcTableList, DataRow, bool> pairResult = null;
			Dictionary<eHistProcTableList, DataRow> dicResult = FindHistory(strMESID, strPalletID, true);

			try
			{
				foreach (eHistProcTableList procTbl in Enum.GetValues(typeof(eHistProcTableList)))
				{
					DataRow dtRow = dicResult[procTbl];

					if (dtRow == null)
					{
						if (pairResult == null)
							pairResult = new Tuple<eHistProcTableList, DataRow, bool>(procTbl, null, true);
					}
					else
					{
						pairResult = new Tuple<eHistProcTableList, DataRow, bool>(procTbl, dtRow, false);

						break;
					}
				}
			}
			catch (Exception ex)
			{
				MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
				   @"NgCode<Exception> - NGHistDBFinder - FindNGHistory()\r\n" +
				   ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
			}
			finally { }

			return pairResult;
		}
		public List<string> GetOnloadedPalletIDs(string strMESID)
		{
			string strQuery = $"SELECT PalletID FROM {eHistAllTableList.HIST_ProdLoad.ToString()} WHERE {eHistTableCommonCols.ProdID} = '{strMESID}' ORDER BY {eHistTableCommonCols.UpdateDT.ToString()} DESC";

			DataSet dtSet = refPCAdaptor.WaitSystemQuery(strQuery);

			List<string> vstrPalletID = (from dtResult in dtSet.Tables[0].AsEnumerable() 											
											let strResult = dtResult[eHistTableCommonCols.PalletID.ToString()].ToString().Trim()
										 select strResult).ToList();

			return vstrPalletID;
		}
		public List<string> GetNGCodeHistory(string strMESID)
		{
			List<string> vstrNGCodes = null;

			try
			{
                string strQuery = $"SELECT TOP 100 NGCode FROM {eHistAllTableList.HIST_ProdUnload.ToString()} WHERE {eHistTableCommonCols.ProdID} = '{strMESID}' ORDER BY {eHistTableCommonCols.UpdateDT.ToString()} DESC";

                DataSet dtSet = refPCAdaptor.WaitSystemQuery(strQuery);

				vstrNGCodes = (from dtResult in dtSet.Tables[0].AsEnumerable()
                               let strResult = dtResult[eHist_ProdUnload.NGCode.ToString()].ToString().Trim()
                               select strResult).ToList();
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
				   @"NgCode<Exception> - NGHistDBFinder - GetNGCodeHistory()\r\n" +
                   ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
            }
            finally { }

            return vstrNGCodes;
		}
		string SearchRecentResultQuery(string strTable, string strMESID)
		{
			string strQuery = $"SELECT * FROM {strTable}";

			return strQuery;
		}
		public string GetCurrentPalletID(string strMESID)
		{
			string strColPalletID = "PalletID";
			string strProdLoadState = "STAT_ProdLoad";
			string strQuery = $"SELECT {strColPalletID} FROM {strProdLoadState} WHERE {eStat_ProdLoad.ProdID} = '{strMESID}'";

			DataSet dsResult = refPCAdaptor.WaitSystemQuery(QueryProcessList);

			List<string> vstrPalletID = (from dtResult in dsResult.Tables[0].AsEnumerable() 
												where dtResult[strColPalletID].ToString().Trim() == strMESID
												let strResult = dtResult[strColPalletID].ToString().Trim()
											select strResult).ToList();

			if(vstrPalletID.Count <= 0)
				return string.Empty;

			return vstrPalletID[0];
		}
		public DataTable GetProcessList()
		{
			DataSet dsResult = refPCAdaptor.WaitSystemQuery(QueryProcessList);

			return dsResult.Tables[0];
		}

		string QueryProcessList = $"SELECT * FROM {DBSchemaMap.ProcessListTableName}";	
	}
}
