//using Adaptation.Helpers;
//using Adaptation.Shared;
//using Adaptation.Shared.Deposition;
//using log4net;
//using System;
//using System.Collections.Generic;
//using System.IO;
//using System.Linq;
//using System.Text;
//using System.Text.Json;
//using System.Threading;

//namespace Adaptation.FileHandlers
//{

//    public partial class FileRead : ILogic
//    {

//        private ConfigData _ConfigData;

//        public FileRead()
//        {
//            Logistics = new Logistics();
//            _Log = LogManager.GetLogger(typeof(FileRead));
//        }

//        public ILogic ShallowCopy() => (ILogic)MemberwiseClone();

//        public void WaitForThread() => WaitForThread(thread: null, threadExceptions: null);

//        public Tuple<string, ConfigDataBase> GetOpenInsightTuple()
//        {
//            Tuple<string, ConfigDataBase> results = new(_ConfigData.OpenInsightGaNViewer, _ConfigData);
//            return results;
//        }

//        public Tuple<string, JsonElement?, List<FileInfo>> GetExtractResult(string reportFullPath, string eventName)
//        {
//            Tuple<string, JsonElement?, List<FileInfo>> results;
//            _FileParameter.Clear();
//            DateTime dateTime = DateTime.Now;
//            if (_ConfigData.IsEvent && _ConfigData.Duplicator is null)
//                results = GetExtractResult(reportFullPath);
//            else if (_ConfigData.Duplicator.HasValue)
//                results = GetDuplicatorExtractResult(reportFullPath, dateTime);
//            else
//            {
//                results = new Tuple<string, JsonElement?, List<FileInfo>>(string.Empty, null, new List<FileInfo>());
//                SupportExtractResult(reportFullPath);
//            }
//            if (results.Item2 is null)
//                results = new Tuple<string, JsonElement?, List<FileInfo>>(results.Item1, JsonSerializer.Deserialize<JsonElement>("[]"), results.Item3);
//            int count = results.Item2.Value.GetArrayLength();
//            if (count > 0 && _ConfigData.EafHosted)
//                WritePDSF(results.Item2.Value);
//            UpdateLastTicksDuration(DateTime.Now.Ticks - dateTime.Ticks);
//            return results;
//        }

//        private Tuple<string, JsonElement?, List<FileInfo>> GetExtractResult(string reportFullPath)
//        {
//            Tuple<string, JsonElement?, List<FileInfo>> results = new(string.Empty, null, new List<FileInfo>());
//            FileInfo fileInfo = new(reportFullPath);
//            Logistics = new Logistics(ConfigData.NullData, _ConfigData.CellNames, _ConfigData.MesEntities, fileInfo, useSplitForMID: false);
//            SetFileParameterLotIDToLogisticsMID();
//            ProcessData processData = new(this, _ConfigData, results.Item3);
//            if (!processData.AnalysisTXTResults.Any() && !processData.AnalysisXMLResults.Any() && !processData.RunMeasurements.Any())
//                throw new Exception("No Data");
//            if (processData.AnalysisTXTResults.Any())
//                Logistics.MID = processData.AnalysisTXTResults[0].LotID;
//            else if (processData.RunMeasurements.Any())
//            {
//                if (!processData.RunMeasurements[0].MID.StartsWith(_ConfigData.FileConnectorConfiguration.SourceFileFilter.Substring(0, 2)))
//                    Logistics.MID = _ConfigData.FileConnectorConfiguration.SourceFileFilter.Substring(0, 2);
//                else
//                    Logistics.MID = processData.RunMeasurements[0].MID;
//            }
//            string reactor = _ConfigData.GetCurrentReactor(this);
//            if (string.IsNullOrEmpty(reactor))
//                throw new Exception("Unable to match Current Reactor");
//            Logistics.ProcessJobID = reactor;
//            if (processData.RunMeasurements.Any())
//                SetFileParameterLotIDToLogisticsMID();
//            results = processData.GetResults(this, _ConfigData, results.Item3);
//            return results;
//        }

//        private Tuple<string, JsonElement?, List<FileInfo>> GetDuplicatorExtractResult(string reportFullPath, DateTime dateTime)
//        {
//            Tuple<string, JsonElement?, List<FileInfo>> results;
//            Tuple<string, string[], string[]> pdsf = ProcessDataStandardFormat.GetLogisticsColumnsAndBody(reportFullPath);
//            Logistics = new Logistics(reportFullPath, pdsf.Item1);
//            SetFileParameterLotIDToLogisticsMID();
//            JsonElement pdsfBodyValues = ProcessDataStandardFormat.GetArray(pdsf);
//            results = new Tuple<string, JsonElement?, List<FileInfo>>(pdsf.Item1, pdsfBodyValues, new List<FileInfo>());
//            List<Duplicator.Description> processDataDescriptions = _ConfigData.GetProcessDataDescriptions(pdsfBodyValues);
//            Dictionary<Test, List<Duplicator.Description>> keyValuePairs = ProcessData.GetKeyValuePairs(_ConfigData, pdsfBodyValues, processDataDescriptions, extra: false);
//            bool isDummyRun = (ConfigData.DummyRuns.Any() && ConfigData.DummyRuns.ContainsKey(Logistics.JobID) && ConfigData.DummyRuns[Logistics.JobID].Any() && (from l in ConfigData.DummyRuns[Logistics.JobID] where l == Logistics.Sequence select 1).Any());
//            if (isDummyRun)
//            {
//                try
//                { File.SetLastWriteTime(reportFullPath, dateTime); }
//                catch (Exception) { }
//            }
//            bool isMock = _ConfigData.Duplicator.Value is ConfigData.Level.IsR69TXTAPCMock or ConfigData.Level.IsR71HealthCp2MgAPCMock or ConfigData.Level.IsR69TXTIQSMock or ConfigData.Level.IsR71XMLIQSMock;
//            if ((isDummyRun || _Configuration.FileScanningIntervalInSeconds > 0) && _ConfigData.Duplicator.Value != ConfigData.Level.IsArchive && !isMock)
//            {
//                string successDirectory;
//                string duplicateDirectory;
//                string[] segments = Path.GetFileNameWithoutExtension(reportFullPath).Split('_');
//                if (_ConfigData.Duplicator.Value != ConfigData.Level.IsXToAPC)
//                    successDirectory = string.Empty;
//                else
//                {
//                    successDirectory = string.Concat(Path.GetDirectoryName(_Configuration.TargetFileLocation), @"\ViewerPath");
//                    if (!Directory.Exists(successDirectory))
//                        _ = Directory.CreateDirectory(successDirectory);
//                }
//                if (_ConfigData.Duplicator.Value is ConfigData.Level.IsXToSPaCe or ConfigData.Level.IsXToSPaCeVillach)
//                    duplicateDirectory = _Configuration.TargetFileLocation;
//                else
//                    duplicateDirectory = string.Concat(_Configuration.TargetFileLocation, @"\", segments[0]);
//                if (segments.Length > 2)
//                    duplicateDirectory = string.Concat(duplicateDirectory, @"-", segments[2]);
//                if (!Directory.Exists(duplicateDirectory))
//                    _ = Directory.CreateDirectory(duplicateDirectory);
//                string logisticsSequence = Logistics.Sequence.ToString();
//                List<Tuple<IScopeInfo, string>> tuples = new();
//                string duplicateFile = string.Concat(duplicateDirectory, @"\", Path.GetFileName(reportFullPath));
//                if (isDummyRun || _ConfigData.Duplicator.Value != ConfigData.Level.IsXToArchive)
//                {
//                    Test test;
//                    List<Tuple<IScopeInfo, string>> linesCollection;
//                    foreach (KeyValuePair<Test, List<Duplicator.Description>> keyValuePair in keyValuePairs)
//                    {
//                        test = keyValuePair.Key;
//                        switch (test)
//                        {
//                            case Test.GRATXTCenter:
//                            case Test.GRATXTEdge:
//                            case Test.LogbookCAC:
//                            case Test.GrowthRateXML:
//                                if (_ConfigData.EafHosted)
//                                {
//                                    if (_ConfigData.Duplicator.Value != ConfigData.Level.IsXToIQS || reportFullPath.EndsWith("_Health_Cp2Mg.pdsf"))
//                                        File.Copy(reportFullPath, duplicateFile, overwrite: true);
//                                    else
//                                    {
//                                        linesCollection = ProcessData.GetLines(this, _ConfigData, pdsfBodyValues, test);
//                                        foreach (Tuple<IScopeInfo, string> tuple in linesCollection)
//                                            tuples.Add(new Tuple<IScopeInfo, string>(tuple.Item1, tuple.Item2));
//                                    }
//                                }
//                                break;
//                            default:
//                                throw new Exception();
//                        }
//                    }
//                }
//                if (_ConfigData.Duplicator.Value != ConfigData.Level.IsXToArchive)
//                    Shared0413(dateTime, isDummyRun, successDirectory, duplicateDirectory, tuples, duplicateFile);
//                else
//                {
//                    string destinationDirectory = WriteScopeInfo(_ConfigData.ProgressPath, Logistics, dateTime, duplicateDirectory, tuples);
//                    if (isDummyRun)
//                        Shared0607(reportFullPath, duplicateDirectory, logisticsSequence, destinationDirectory);
//                }
//            }
//            return results;
//        }

//        private void SupportExtractResult(string reportFullPath)
//        {
//            ConfigData.ConnectionAction connectionAction = _ConfigData.GetConnectionActionValue();
//            switch (connectionAction)
//            {
//                case ConfigData.ConnectionAction.MoveDLGFile:
//                case ConfigData.ConnectionAction.MoveDLGFileForParse:
//                case ConfigData.ConnectionAction.MoveTXTOrXMLFile:
//                case ConfigData.ConnectionAction.MoveXMLFile:
//                    break;
//                case ConfigData.ConnectionAction.RenameTXTFile:
//                    if (reportFullPath.Contains('#'))
//                    {
//                        string fourZeroHashTag = "40#";
//                        string sixThreeHashTag = "63#";
//                        string nineFiveHashTag = "95#";
//                        string[] segments = Path.GetFileNameWithoutExtension(reportFullPath).Split('_');
//                        if ((from l in segments where l != fourZeroHashTag && l != sixThreeHashTag && l != nineFiveHashTag select l).Any())
//                        {
//                            string wavelengthGroup;
//                            string text = File.ReadAllText(reportFullPath);
//                            if (text.Contains("wavelength    40"))
//                                wavelengthGroup = "40#";
//                            else if (text.Contains("wavelength    63"))
//                                wavelengthGroup = "63#";
//                            else if (text.Contains("wavelength    95"))
//                                wavelengthGroup = "95#";
//                            else
//                                wavelengthGroup = "###";
//                            StringBuilder stringBuilder = new();
//                            for (int i = 0; i < segments.Length; i++)
//                            {
//                                _ = stringBuilder.Append(segments[i]).Append('_');
//                                if (i == 2)
//                                    _ = stringBuilder.Append(wavelengthGroup).Append('_');
//                            }
//                            if (stringBuilder.Length > 0)
//                                _ = stringBuilder.Remove(stringBuilder.Length - 1, 1);
//                            string fileName = Path.Combine(Path.GetDirectoryName(reportFullPath), stringBuilder.ToString());
//                            File.WriteAllText(fileName, text);
//                            File.Delete(reportFullPath);
//                        }
//                    }
//                    break;
//                case ConfigData.ConnectionAction.SplitCACFile:
//                    ProcessData.SplitCACFile(_ConfigData, reportFullPath);
//                    break;
//                case ConfigData.ConnectionAction.MoveCACFile:
//                    FileInfo fileInfo = new(Path.Combine(_ConfigData.FileConnectorConfiguration.TargetFileLocation, Path.GetFileName(reportFullPath)));
//                    if (fileInfo.Exists && new FileInfo(reportFullPath).LastWriteTime > fileInfo.LastWriteTime)
//                    {
//                        try
//                        { File.Delete(fileInfo.FullName); }
//                        catch (Exception) { }
//                        Thread.Sleep(500);
//                    }
//                    break;
//                case ConfigData.ConnectionAction.WritePDSFFile:
//                    string mesEntity = _ConfigData.CellName;
//                    FileInfo sourceFileInfo = new(reportFullPath);
//                    string extension = string.Concat(".", _ConfigData.FileConnectorConfiguration.TargetFileName.Split('.')[1]);
//                    string ticks = string.Concat(_ConfigData.FileConnectorConfiguration.TargetFileLocation, @"\", sourceFileInfo.LastWriteTime.Ticks);
//                    FileInfo pdsfFileInfo = new(string.Concat(_ConfigData.FileConnectorConfiguration.TargetFileLocation, @"\", mesEntity, "_", sourceFileInfo.LastWriteTime.ToString("yyMMddHHmmssfff"), "_dlg", extension));
//                    if (pdsfFileInfo.Exists)
//                        throw new Exception("Destination file already exists!");
//                    string pdsfText = ProcessData.GetPDSFTextFromDLG(_ConfigData, mesEntity, sourceFileInfo, useSetpoint: false, writeFiles: false, fullDateTime: false, backFill: true);
//                    File.WriteAllText(ticks, pdsfText);
//                    File.SetLastWriteTime(ticks, sourceFileInfo.LastWriteTime);
//                    File.Move(ticks, pdsfFileInfo.FullName);
//                    break;
//                case ConfigData.ConnectionAction.RaiseCACFileEvent:
//                case ConfigData.ConnectionAction.RaiseTXTFileEvent:
//                case ConfigData.ConnectionAction.RaiseXMLFileEvent:
//                    throw new Exception();
//                default:
//                    throw new Exception();
//            }
//        }

//        private void MoveArchive()
//        {
//            const int midLength = 7;
//            const int midSegment = 5;
//            const char midPadding = '0';
//            string destinationDirectory;
//            string logisticsSequence = Logistics.Sequence.ToString();
//            string group = Logistics.MID.PadLeft(midLength, midPadding).Substring(0, midSegment).PadRight(midLength, midPadding);
//            string rootDestinationDirectory = string.Concat(Path.GetDirectoryName(_Configuration.TargetFileLocation), @"\", Logistics.MesEntity);
//            string[] matchDirectories = new string[] { GetDirectoriesRecursively(rootDestinationDirectory, logisticsSequence).FirstOrDefault() };
//            if (matchDirectories.Length == 0 || string.IsNullOrEmpty(matchDirectories[0]))
//                matchDirectories = Directory.GetDirectories(rootDestinationDirectory, string.Concat('*', logisticsSequence, '*'), SearchOption.AllDirectories);
//            if ((matchDirectories is null) || matchDirectories.Length != 1)
//                throw new Exception("Didn't find directory by logistics sequence");
//            if (matchDirectories[0].Contains("_processing failed"))
//                destinationDirectory = string.Concat(rootDestinationDirectory, @"\", "_Process_Failed");
//            else if (matchDirectories[0].Contains("_in process"))
//                destinationDirectory = string.Concat(rootDestinationDirectory, @"\All_other_files_and_folders");
//            else if (matchDirectories[0].Contains("_processed"))
//                destinationDirectory = string.Concat(rootDestinationDirectory, @"\- Archive\", group);
//            else
//                throw new Exception();
//            if (!Directory.Exists(destinationDirectory))
//                _ = Directory.CreateDirectory(destinationDirectory);
//            string directoryName = Path.GetFileName(matchDirectories[0]);
//            if (directoryName != logisticsSequence)
//                throw new Exception("directoryName != logisticsSequence");
//            else
//            {
//                string sourceDirectoryName = Path.GetDirectoryName(matchDirectories[0]);
//                string destinationDirectoryName = string.Concat(destinationDirectory, @"\", Path.GetFileName(sourceDirectoryName));
//                if (destinationDirectoryName != sourceDirectoryName)
//                    Directory.Move(sourceDirectoryName, destinationDirectoryName);
//            }
//        }

//        public void Move(string reportFullPath, Tuple<string, JsonElement?, List<FileInfo>> extractResults, Exception exception = null)
//        {
//            Shared1872(reportFullPath, exception);
//            bool isErrorFile = exception is not null;
//            if (!isErrorFile && _ConfigData.Duplicator.HasValue)
//            {
//                if (_ConfigData.Duplicator.Value == ConfigData.Level.IsXToArchive)
//                    Shared0192(reportFullPath);
//                else if (_ConfigData.EafHosted && _ConfigData.Duplicator.Value == ConfigData.Level.IsArchive)
//                    MoveArchive();
//                if (_ConfigData.EafHosted && !string.IsNullOrEmpty(_ConfigData.ProgressPath))
//                    CreateProgressDirectory(_ConfigData.ProgressPath, Logistics, (int?)_ConfigData.Duplicator, exceptionLines: null);
//            }
//        }

//    }

//}