using Adaptation.Eaf.Management.ConfigurationData.CellAutomation;
using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using Adaptation.Shared;
using Adaptation.Shared.Duplicator;
using Adaptation.Shared.Methods;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;

namespace Adaptation.FileHandlers.DEP08SIASM;

public class FileRead : Shared.FileRead, IFileRead
{

    private readonly bool _IsDummy;
    private readonly bool _IsXToAPC;
    private readonly bool _IsXToIQS;
    private readonly bool _IsXToSPaCe;
    private readonly bool _IsXToSPaCeVillach;
    private readonly Dictionary<string, string> _CellNames;

    public FileRead(ISMTP smtp, Dictionary<string, string> fileParameter, string cellInstanceName, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList<ModelObjectParameterDefinition> modelObjectParameters, string equipmentDictionaryName, Dictionary<string, List<long>> dummyRuns, bool useCyclicalForDescription, bool isEAFHosted) :
        base(new Description(), false, smtp, fileParameter, cellInstanceName, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, useCyclicalForDescription, isEAFHosted)
    {
        _MinFileLength = 10;
        _NullData = string.Empty;
        _Logistics = new Logistics(this);
        if (_FileParameter is null)
            throw new Exception(cellInstanceConnectionName);
        if (_ModelObjectParameterDefinitions is null)
            throw new Exception(cellInstanceConnectionName);
        if (!_IsDuplicator)
            throw new Exception(cellInstanceConnectionName);
        _IsDummy = _Hyphens == (int)Hyphen.IsDummy;
        _IsXToAPC = _Hyphens == (int)Hyphen.IsXToAPC;
        _IsXToIQS = _Hyphens == (int)Hyphen.IsXToIQS;
        _CellNames = new Dictionary<string, string>();
        _IsXToSPaCe = _Hyphens == (int)Hyphen.IsXToSPaCe;
        _IsXToSPaCeVillach = _Hyphens == (int)Hyphen.IsXToSPaCeVillach;
        ModelObjectParameterDefinition[] cellInstanceCollection = GetProperties(cellInstanceConnectionName, modelObjectParameters, "CellInstance.", ".Path");
        foreach (ModelObjectParameterDefinition modelObjectParameterDefinition in cellInstanceCollection)
            _CellNames.Add(modelObjectParameterDefinition.Name.Split('.')[1], modelObjectParameterDefinition.Value);
    }

    void IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, Exception exception) => Move(extractResults, exception);

    void IFileRead.WaitForThread() => WaitForThread(thread: null, threadExceptions: null);

    string IFileRead.GetEventDescription()
    {
        string result = _Description.GetEventDescription();
        return result;
    }

    List<string> IFileRead.GetHeaderNames()
    {
        List<string> results = _Description.GetHeaderNames();
        return results;
    }

    string[] IFileRead.Move(Tuple<string, Test[], JsonElement[], List<FileInfo>> extractResults, string to, string from, string resolvedFileLocation, Exception exception)
    {
        string[] results = Move(extractResults, to, from, resolvedFileLocation, exception);
        return results;
    }

    JsonProperty[] IFileRead.GetDefault()
    {
        JsonProperty[] results = _Description.GetDefault(this, _Logistics);
        return results;
    }

    Dictionary<string, string> IFileRead.GetDisplayNamesJsonElement()
    {
        Dictionary<string, string> results = _Description.GetDisplayNamesJsonElement(this);
        return results;
    }

    List<IDescription> IFileRead.GetDescriptions(IFileRead fileRead, List<Test> tests, IProcessData processData)
    {
        List<IDescription> results = _Description.GetDescriptions(fileRead, _Logistics, tests, processData);
        return results;
    }

    Tuple<string, Test[], JsonElement[], List<FileInfo>> IFileRead.GetExtractResult(string reportFullPath, string eventName)
    {
        Tuple<string, Test[], JsonElement[], List<FileInfo>> results;
        if (string.IsNullOrEmpty(eventName))
            throw new Exception();
        _ReportFullPath = reportFullPath;
        DateTime dateTime = DateTime.Now;
        results = GetExtractResult(reportFullPath, dateTime);
        if (results.Item3 is null)
            results = new Tuple<string, Test[], JsonElement[], List<FileInfo>>(results.Item1, Array.Empty<Test>(), JsonSerializer.Deserialize<JsonElement[]>("[]"), results.Item4);
        if (results.Item3.Length > 0 && _IsEAFHosted)
            WritePDSF(this, results.Item3);
        UpdateLastTicksDuration(DateTime.Now.Ticks - dateTime.Ticks);
        return results;
    }

    Tuple<string, Test[], JsonElement[], List<FileInfo>> IFileRead.ReExtract()
    {
        Tuple<string, Test[], JsonElement[], List<FileInfo>> results;
        List<string> headerNames = _Description.GetHeaderNames();
        Dictionary<string, string> keyValuePairs = _Description.GetDisplayNamesJsonElement(this);
        results = ReExtract(this, headerNames, keyValuePairs);
        return results;
    }

    void IFileRead.CheckTests(Test[] tests, bool extra)
    {
        if (_Description is not Description)
            throw new Exception();
    }

    protected static List<Description> GetDescriptions(JsonElement[] jsonElements)
    {
        List<Description> results = new();
        Description description;
        JsonSerializerOptions jsonSerializerOptions = new() { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString };
        foreach (JsonElement jsonElement in jsonElements)
        {
            if (jsonElement.ValueKind != JsonValueKind.Object)
                throw new Exception();
            description = JsonSerializer.Deserialize<Description>(jsonElement.ToString(), jsonSerializerOptions);
            results.Add(description);
        }
        return results;
    }

    private Tuple<string, Test[], JsonElement[], List<FileInfo>> GetExtractResult(string reportFullPath, DateTime dateTime)
    {
        Tuple<string, Test[], JsonElement[], List<FileInfo>> results;
        string duplicateDirectory;
        Tuple<string, string[], string[]> pdsf = ProcessDataStandardFormat.GetLogisticsColumnsAndBody(reportFullPath);
        _Logistics = new Logistics(reportFullPath, pdsf.Item1);
        SetFileParameterLotIDToLogisticsMID();
        JsonElement[] jsonElements = ProcessDataStandardFormat.GetArray(pdsf);
        List<Description> descriptions = GetDescriptions(jsonElements);
        Tuple<Test[], Dictionary<Test, List<Shared.Properties.IDescription>>> tuple = GetTuple(this, from l in descriptions select (Shared.Properties.IDescription)l, extra: false);
        results = new Tuple<string, Test[], JsonElement[], List<FileInfo>>(pdsf.Item1, tuple.Item1, jsonElements, new List<FileInfo>());
        bool isDummyRun = _DummyRuns.Any() && _DummyRuns.ContainsKey(_Logistics.JobID) && _DummyRuns[_Logistics.JobID].Any() && (from l in _DummyRuns[_Logistics.JobID] where l == _Logistics.Sequence select 1).Any();
        if (isDummyRun)
        {
            try
            { File.SetLastWriteTime(reportFullPath, dateTime); }
            catch (Exception) { }
        }
        if (isDummyRun || _FileConnectorConfiguration.FileScanningIntervalInSeconds > 0)
        {
            string successDirectory;
            string[] segments = Path.GetFileNameWithoutExtension(reportFullPath).Split('_');
            if (!_IsXToAPC)
                successDirectory = string.Empty;
            else
            {
                successDirectory = string.Concat(Path.GetDirectoryName(_FileConnectorConfiguration.TargetFileLocation), @"\ViewerPath");
                if (!Directory.Exists(successDirectory))
                    _ = Directory.CreateDirectory(successDirectory);
            }
            if (_IsXToSPaCe || _IsXToSPaCeVillach)
                duplicateDirectory = _FileConnectorConfiguration.TargetFileLocation;
            else
                duplicateDirectory = string.Concat(_FileConnectorConfiguration.TargetFileLocation, @"\", segments[0]);
            if (segments.Length > 2)
                duplicateDirectory = string.Concat(duplicateDirectory, @"-", segments[2]);
            if (!Directory.Exists(duplicateDirectory))
                _ = Directory.CreateDirectory(duplicateDirectory);
            List<Tuple<Shared.Properties.IScopeInfo, string>> tuples = new();
            string duplicateFile = string.Concat(duplicateDirectory, @"\", Path.GetFileName(reportFullPath));
            if (isDummyRun)
            {
                foreach (KeyValuePair<Test, List<Shared.Properties.IDescription>> keyValuePair in tuple.Item2)
                    File.Copy(reportFullPath, duplicateFile, overwrite: true);
            }
            if (!isDummyRun && _IsEAFHosted)
                WaitForFileConsumption(_FileConnectorConfiguration.SourceDirectoryCloaking, _Logistics, dateTime, successDirectory, duplicateDirectory, duplicateFile, tuples);
            else
            {
                long breakAfter = DateTime.Now.AddSeconds(_FileConnectorConfiguration.ConnectionRetryInterval.Value).Ticks;
                for (short i = 0; i < short.MaxValue; i++)
                {
                    if (!_IsEAFHosted || DateTime.Now.Ticks > breakAfter)
                        break;
                    Thread.Sleep(500);
                }
            }
        }
        return results;
    }

}