using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

using PsKGaudi;
using PsKGaudi.Parser.PsCCSArea;

using static PsCommon.PsCommon;
using static PsKGaudi.Parser.PsCCS;

using SystemX.Common.Archive;

using static SystemX.Product.ALIS.UI.View.InfoList.UcTestListView;
using System.Threading;

namespace SystemX.Product.PTS.UI.View.Test_List.Infos
{
    public class CpTestlistLoad
    {
        private PsCCSGaudiFile getTestList;

        private byte[] ucTestListByte;

        private psGaudiImformation m_psGaudiInfo = new psGaudiImformation();

        public event EventHandler TestListLoadResultEvent;

        public PsCCSGaudiFile GetPsCCSTestList()
        {
            return getTestList;
        }

        public byte[] GetTestListRawBytes()
        {
            return ucTestListByte;
        }

        public string GetTestListDescription()
        {
            return getTestList.ListTestStep[0].Comment;
        }

        public bool GetTestListLoadState()
        {
            return m_psGaudiInfo.bInfoNormalLoaded;
        }

        public psGaudiImformation psGaudiInfo
        {
            get { return m_psGaudiInfo; }
        }

        public void ExcuteTestListLoad(CVariantInformation ParentInfo)
        {
            m_psGaudiInfo = new psGaudiImformation();

            string strGetCurrentDir = Directory.GetCurrentDirectory();
            Guid uguid = Guid.NewGuid();
            string strTempFileName = @strGetCurrentDir + @"\TempTestList\";

            if (Directory.Exists(strTempFileName) == false)
                Directory.CreateDirectory(strTempFileName);

            strTempFileName += uguid.ToString("B") + ".CpXv" + ParentInfo.Version + ParentInfo.ProdCode;
            //ParentInfo.TestListSelectForCopyRawData = XDataArchive.DecompressGZipByteToByte(ParentInfo.TestListSelectForCopyRawData);
            //File.WriteAllBytes(strTempFileName, (byte[])ParentInfo.TestListSelectForCopyRawData);

            Thread.Sleep(100);

            LoadTestList(strTempFileName, true);
        }

        public bool CheckTestListLoad()
        {
            if (m_psGaudiInfo.bInfoLoading)
            {
                MessageBox.Show("You cannot close the information modification wizard while loading the test list.", "CP-Test List Load", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }

            return true;
        }

        private async Task<bool> LoadTestList(string strFileName, bool bDeleteFile = false)
        {
            m_psGaudiInfo.bInfoNormalLoaded = false;
            m_psGaudiInfo.bInfoLoading = true;

            try
            {
                if (PsCpDef.CheckCPFileExtension(strFileName) && getCPxmlInfo(strFileName))
                {
                    if (m_psGaudiInfo.psVariantTable.GetStrVariantTable.Count > 0)
                    {
                        m_psGaudiInfo.psFileInfo = new PsCCSFileInfo(strFileName);

                        await Task.Delay(100);

                        string getTTNR = ((KeyValuePair<string, string>)m_psGaudiInfo.psVariantTable.GetStrVariantTable[0]).Key;
                        getTestList = await LoadTestListFile(@strFileName, getTTNR);

                        if (getTestList != null)
                        {
                            ucTestListByte = File.ReadAllBytes(strFileName);

                            m_psGaudiInfo.bInfoNormalLoaded = true;

                            TestListLoadResultEvent?.BeginInvoke(true, null, null, null);
                        }
                        else
                            throw new Exception($"Failed to load test list file.");
                    }
                    else
                        throw new Exception($"There is no TTNR information registered in the test list.");
                }
                else
                    throw new Exception($"Not a normal CP TestList.");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "CP-Test List Load", MessageBoxButtons.OK, MessageBoxIcon.Error);

                TestListLoadResultEvent?.BeginInvoke(false, null, null, null);
            }

            await Task.Delay(1);

            if (bDeleteFile)
                File.Delete(strFileName);

            m_psGaudiInfo.bInfoLoading = false;

            return m_psGaudiInfo.bInfoNormalLoaded;
        }

        private async Task<PsCCSGaudiFile> LoadTestListFile(string strFileName, string strTTNR)
        {
            return await Task.Run(async () =>
            {
                await Task.Delay(10);

                return PsCCSGaudiFile.PsCCSPaseDataApi(strFileName, strTTNR);
            });
        }

        private bool getCPxmlInfo(string strfilename)
        {
            try
            {
                XDocument xDoc = XDocument.Load(strfilename);

                PsCCSAreaBasicInfo psBasicInfo = PsCCSAreaBasicInfo.LoadXmlData(xDoc.Root);
                PsCCSAreaTestListInfo psTestListInfo = PsCCSAreaTestListInfo.LoadXmlData(xDoc.Root);
                PsCCSAreaVariantTable psVariantTable = PsCCSAreaVariantTable.LoadXmlData(xDoc.Root);
                PsCCSFileInfo psFileInfo = new PsCCSFileInfo(strfilename);

                m_psGaudiInfo.psBasicInfo = psBasicInfo;
                m_psGaudiInfo.psTestListInfo = psTestListInfo;
                m_psGaudiInfo.psVariantTable = psVariantTable;
                m_psGaudiInfo.psFileInfo = psFileInfo;
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
    }
}
