using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using SystemX.Product.ALIS.UI.View.InfoList;
using System.Data.SqlClient;
using SystemX.Product.ALIS.Interface;
using static SystemX.Product.ALIS.UI.View.ViewCfg;
using DevExpress.XtraGrid.Columns;
using System.Reflection;
using SystemX.Product.ALIS.UI.Subs;
using System.Threading;

using static CpCommon.ExceptionHandler;
using static PsKGaudi.Parser.PsCCS;
using PsKGaudi.Parser.PsCCSSTDFn;
using CpApplication;
using CpApplication.Manager;
using CpCommon;
using CpTesterPlatform.CpLogUtil;
using static PsCommon.PsCommon;
using System.Xml.Linq;
using PsKGaudi.Parser.PsCCSArea;
using PsKGaudi;
using PsKGaudi.Parser.MacroModuleSkel;
using PsKGaudi.Parser.PsCCSSTDFn.Parameters;
using DevExpress.XtraGrid.Views.Base;
using PsKGaudi.Parser.PsCCSSTDFn;
using System.IO;
using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Diagnostics;
using SystemX.Common;
using SystemX.Common.Archive;

namespace SystemX.Product.ALIS.UI.View.InfoList
{
    public class UcTestListViewVariantBasicWorker
    {

    }

    public partial class UcTestListView
    {
        private void RunAsyncVariantInsertUpdateWorker()
        {
            workerTestListVariant.RunWorkerAsync(eEdtType);

            loadForm = new WaitProgressForm();
            loadForm.setDescription("Proceeding ...");
            loadForm.Location = new Point(this.Parent.Width / 2, this.Parent.Height / 2);

            //loadForm.ShowOnTopMode = DevExpress.XtraWaitForm.ShowFormOnTopMode.AboveAll;
            //loadForm.TopLevel = true;
            //loadForm.BringToFront();

            stLoadFormWait.Restart();
            loadForm.ShowDialog();
        }

        /// <summary>
        /// [이전 테스트리스트 새 테스트 리스트 비교하여 처이점이 있을시 버전 업데이트 및 Release VRFY 반영]
        /// * 2022/11/08 추가 : 변경점이 있는 테스트리스트 업데이트시 HIST_TestList 반영 버전 선택 및 버전 선택 다운로드 반영
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PerformTestListVariantReading(object sender, DoWorkEventArgs args)
        {
            if (SelectOpenType != eSelectType.TestListVariant)
                return;

            Thread.Sleep(10);

            bool bProcessResult = true;

            eEditType eSeledtType = (eEditType)((System.ComponentModel.DoWorkEventArgs)args).Argument;

            Stopwatch stMeasTime = new Stopwatch();
            stMeasTime.Start();

            try
            {
                switch (eSeledtType)
                {
                    case eEditType.Insert:
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" PerformTestListVariantReading() Insert", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                        break;
                    case eEditType.Modify:
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" PerformTestListVariantReading() Modify", ConsoleColor.Yellow, LogMessageLevel.DEBUG); 
                        break;
                }
            }
            catch (Exception error)
            {
                bProcessResult = false;

                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" PerformTestListVariantReading() Common Error. " + error.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
            }
            finally
            {
                var setResult = new Tuple<eEditType, bool>(eSeledtType, bProcessResult);

                args.Result = setResult;
            }

            long lMeasTime = stMeasTime.ElapsedMilliseconds;
        }

        private async void ReadingVariantCompleted(object sender, RunWorkerCompletedEventArgs args)
        {
            // Error Check
            if (args.Error != null)
            {
                ;//
            }
            // Worker Cancel
            else if (args.Cancelled)
            {
                ;//
            }
            // Success
            else
            {
                var getResult = args.Result as Tuple<eEditType, bool>;

                eEditType getType = getResult.Item1;
                bool bGetProcessResult = getResult.Item2;

                //정상 처리 상태 일때만.
                if (bGetProcessResult)
                {
                    switch (getType)
                    {
                        case eEditType.Insert:
                            break;
                        case eEditType.Modify:
                            SqlUpdateProdVariant();
                            break;
                    }
                }
            }

            if (stLoadFormWait.ElapsedMilliseconds <= 100)
            {
                int iremainTime = 1000 - (int)stLoadFormWait.ElapsedMilliseconds;

                await Task.Delay(iremainTime); //Thread.Sleep(iremainTime); 
            }

            if (loadForm != null)
            {
                loadForm.Close();
                loadForm = null;
            }
        }

        private bool SqlUpdateProdVariant()
        {
            bool bUpdatedResult = true;

            string strSetRegDT, strSetUpdateDT;

            strSetRegDT = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            strSetUpdateDT = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            SqlCommand cmd = new SqlCommand();

            string columns = string.Empty;

            columns = "ProdNo_P,RegDT,RegUser,UpdateDT,UpdateUser,GroupNo,Comment,Description,TestListFileNo";//,UseTLPosition";

            Type type = typeof(CVariantInformation);
            FieldInfo[] f = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            StringBuilder sb = new StringBuilder();
            sb.Append("UPDATE [PROD_Variant] SET ");

            foreach (string str in columns.Split(','))
            {
                int idx = -1;
                idx = Array.FindIndex(f, x => x.Name.IndexOf(str) >= 0);

                if (str == "RegDT" || str == "UpdateDT")
                {
                    string strGetDateTime = ctrlDB.SetConvertDateTime(f[idx].GetValue(SelectTestListVariantInfo).ToString());

                    sb.Append(str + " = '" + strGetDateTime + "', ");

                    if (str == "RegDT")
                        strSetRegDT = strGetDateTime;
                    else if (str == "UpdateDT")
                        strSetUpdateDT = strGetDateTime;
                }
                /*
                else if(str == "UseTLPosition")
                    sb.Append(str + " = 0, ");
                */
                else
                    sb.Append(str + " = '" + f[idx].GetValue(SelectTestListVariantInfo) + "', ");
            }
            sb = sb.Remove(sb.Length - 2, 1);
            sb.Append("WHERE No = " + AbsoluteUniqueNo + ";");

            cmd = new SqlCommand(sb.ToString(), ctrlDB.GetConnSqlCmd().Connection);

            try
            {
                int EffectRows = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                bUpdatedResult = false;

                MessageBox.Show(ex.Message, "SqlUpdateProdVariant [PROD_Variant] - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return bUpdatedResult;
        }
    }
}
