using Library.Ifx.Eaf.EquipmentConnector.File.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; namespace Shared.Metrology; public class ConfigDataBase { public bool UseCyclicalForDescription { get; protected set; } public Dictionary CellNames { get; protected set; } public Dictionary MesEntities { get; protected set; } public IProcessDataDescription ProcessDataDescription { get; protected set; } public bool IsEvent { get; private set; } public EventName EventName => _EventName; public bool EafHosted { get; private set; } public string CellName { get; private set; } public bool IsSourceTimer { get; private set; } public EquipmentType EquipmentType => _EquipmentType; public string EquipmentElementName { get; private set; } public bool IsDatabaseExportToIPDSF { get; private set; } public EquipmentType? EquipmentConnection => _EquipmentConnection; public FileConnectorConfiguration FileConnectorConfiguration { get; private set; } protected readonly EventName _EventName; protected readonly EquipmentType _EquipmentType; protected readonly EquipmentType? _EquipmentConnection; protected readonly Dictionary _Reactors; public ConfigDataBase(string cellName, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, bool isEAFHosted) { CellName = cellName; EafHosted = isEAFHosted; EquipmentType equipmentTypeValue; _Reactors = new Dictionary(); CellNames = new Dictionary(); MesEntities = new Dictionary(); EquipmentElementName = cellInstanceConnectionName; FileConnectorConfiguration = fileConnectorConfiguration; string[] segments = parameterizedModelObjectDefinitionType.Split('.'); IsSourceTimer = (fileConnectorConfiguration.SourceFileFilter.StartsWith("*Timer.txt")); string cellInstanceConnectionNameBase = cellInstanceConnectionName.Replace("-", string.Empty); IsDatabaseExportToIPDSF = (fileConnectorConfiguration.SourceFileLocation.Contains("DatabaseExport")); if (!Enum.TryParse(segments[segments.Length - 1], out EventName eventNameValue)) throw new Exception(cellInstanceConnectionName); if (!Enum.TryParse(cellInstanceConnectionNameBase, out equipmentTypeValue)) _EquipmentConnection = null; else _EquipmentConnection = equipmentTypeValue; string suffix = eventNameValue switch { EventName.FileRead => string.Empty, EventName.FileReadDaily => "_Daily", EventName.FileReadWeekly => "_Weekly", EventName.FileReadMonthly => "_Monthly", EventName.FileReadVerification => "_Verification", _ => throw new Exception(cellInstanceConnectionName), }; string parameterizedModelObjectDefinitionTypeAppended = string.Concat(segments[0], suffix); IsEvent = cellInstanceConnectionNameBase != parameterizedModelObjectDefinitionTypeAppended; _EventName = eventNameValue; if (!Enum.TryParse(parameterizedModelObjectDefinitionTypeAppended, out equipmentTypeValue)) throw new Exception(cellInstanceConnectionName); _EquipmentType = equipmentTypeValue; if (!isEAFHosted && equipmentTypeName != parameterizedModelObjectDefinitionTypeAppended) throw new Exception(cellInstanceConnectionName); } public string GetEventName() { string result = EventName.ToString(); return result; } public string GetEquipmentType() { string result = EquipmentConnection.ToString(); return result; } public string GetEventDescription() { string result = ProcessDataDescription.GetEventDescription(); return result; } public IProcessDataDescription GetDefault(ILogic logic) { IProcessDataDescription result = ProcessDataDescription.GetDefault(logic, this); return result; } public IProcessDataDescription GetDisplayNames(ILogic logic) { IProcessDataDescription result = ProcessDataDescription.GetDisplayNames(logic, this); return result; } public List GetDetailNames(ILogic logic) { List results = ProcessDataDescription.GetDetailNames(logic, this); return results; } public List GetHeaderNames(ILogic logic) { List results = ProcessDataDescription.GetHeaderNames(logic, this); return results; } public List GetNames(ILogic logic) { List results = ProcessDataDescription.GetNames(logic, this); return results; } public List GetPairedParameterNames(ILogic logic) { List results = ProcessDataDescription.GetPairedParameterNames(logic, this); return results; } public List GetParameterNames(ILogic logic) { List results = ProcessDataDescription.GetParameterNames(logic, this); return results; } public List GetDescription(ILogic logic, List tests, IProcessData iProcessData) { List results = ProcessDataDescription.GetDescription(logic, this, tests, iProcessData); return results; } public string GetCurrentReactor(ILogic logic) { string result = string.Empty; foreach (KeyValuePair keyValuePair in _Reactors) { foreach (string filePrefix in keyValuePair.Value.Split('|')) { if (logic.Logistics.MID.StartsWith(filePrefix) || (EventName != EventName.FileRead && MesEntities.ContainsKey(logic.Logistics.JobID) && keyValuePair.Value == MesEntities[logic.Logistics.JobID])) { result = keyValuePair.Key; break; } } } if (string.IsNullOrEmpty(result) && _Reactors.Count == 1) result = _Reactors.ElementAt(0).Key; return result; } protected JsonElement GetDefaultJsonElement(ILogic logic) { JsonElement result; IProcessDataDescription processDataDescription = ProcessDataDescription.GetDefault(logic, this); string json = JsonSerializer.Serialize(processDataDescription, processDataDescription.GetType()); object @object = JsonSerializer.Deserialize(json); result = (JsonElement)@object; return result; } public Dictionary>> GetParameterInfo(ILogic logic, bool allowNull) { Dictionary>> results = new(); string description; Enum param; Tuple tuple; JsonElement defaultJsonElement = GetDefaultJsonElement(logic); Dictionary keyValuePairs = GetDisplayNamesJsonElement(logic); foreach (JsonProperty jsonProperty in defaultJsonElement.EnumerateObject()) { if (jsonProperty.Value.ValueKind == JsonValueKind.Null && !allowNull) throw new Exception(); if (jsonProperty.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array) { description = string.Empty; param = Description.Param.StructuredType; //jValue = jObject.Value("Item1"); throw new NotImplementedException("Item1"); } else { param = jsonProperty.Value.ValueKind switch { JsonValueKind.String => Description.Param.String, JsonValueKind.Number => Description.Param.Double, JsonValueKind.True or JsonValueKind.False => Description.Param.Boolean, JsonValueKind.Null => Description.Param.String, _ => Description.Param.StructuredType, }; } if (!keyValuePairs.ContainsKey(jsonProperty.Name)) description = string.Empty; else description = keyValuePairs[jsonProperty.Name]; tuple = new Tuple(param, jsonProperty.Name, description, jsonProperty.Value.ToString()); if (!results.ContainsKey(jsonProperty.Name)) results.Add(jsonProperty.Name, new List>()); results[jsonProperty.Name].Add(tuple); } return results; } protected void WriteExportAliases(ILogic logic, string cellName, string equipmentElementName) { int i = 0; Enum param; object value; Enum[] @params; string description; StringBuilder stringBuilder = new(); string shareRoot = @"\\messv02ecc1.ec.local\EC_EDA"; string shareDirectory = string.Concat(shareRoot, @"\Staging\Pdsf\", cellName, @"\ExportAliases\", equipmentElementName); Dictionary>> keyValuePairs; if (logic is not null) keyValuePairs = GetParameterInfo(logic, allowNull: false); else keyValuePairs = new Dictionary>>(); _ = stringBuilder.AppendLine("\"AliasName\";\"Condition\";\"EventId\";\"ExceptionId\";\"Formula\";\"HardwareId\";\"OrderId\";\"ParameterName\";\"Remark\";\"ReportName\";\"SourceId\";\"Use\""); if (!Directory.Exists(shareRoot)) return; if (!Directory.Exists(shareDirectory)) _ = Directory.CreateDirectory(shareDirectory); string shareFile = string.Concat(shareDirectory, @"\", DateTime.Now.Ticks, ".csv"); foreach (KeyValuePair>> keyValuePair in keyValuePairs) { i += 1; @params = (from l in keyValuePair.Value select l.Item1).Distinct().ToArray(); if (@params.Length != 1) throw new Exception(); if (keyValuePair.Value[0].Item2 != keyValuePair.Key) throw new Exception(); param = @params[0]; if (param is not Description.Param.String) _ = stringBuilder.AppendLine($"\"{keyValuePair.Key}\";\"\";\"\";\"\";\"\";\"\";\"{i}\";\"{cellName}/{EquipmentElementName}/{keyValuePair.Key}\";\"\";\"{cellName}/{EquipmentElementName}/{EventName}\";\"\";\"True\""); else { description = keyValuePair.Value[0].Item3.Split('|')[0]; if (string.IsNullOrEmpty(description)) continue; value = keyValuePair.Value[0].Item4; _ = stringBuilder.AppendLine($"\"'{description}'\";\"\";\"\";\"\";\"\";\"\";\"{i}\";\"{cellName}/{EquipmentElementName}/{value}\";\"\";\"{cellName}/{EquipmentElementName}/{EventName}\";\"\";\"True\""); } } if (keyValuePairs.Any()) File.WriteAllText(shareFile, stringBuilder.ToString()); } public Dictionary GetDisplayNamesJsonElement(ILogic logic) { Dictionary results = new(); IProcessDataDescription processDataDescription = ProcessDataDescription.GetDisplayNames(logic, this); string json = JsonSerializer.Serialize(processDataDescription, processDataDescription.GetType()); JsonElement jsonElement = JsonSerializer.Deserialize(json); foreach (JsonProperty jsonProperty in jsonElement.EnumerateObject()) { if (!results.ContainsKey(jsonProperty.Name)) results.Add(jsonProperty.Name, string.Empty); if (jsonProperty.Value is JsonElement jsonPropertyValue) results[jsonProperty.Name] = jsonPropertyValue.ToString(); } return results; } public List GetIgnoreParameterNames(ILogic logic, Test test, bool includePairedParameterNames) { List results = ProcessDataDescription.GetIgnoreParameterNames(logic, this, test); if (includePairedParameterNames) { string value; List pairedParameterNames = ProcessDataDescription.GetPairedParameterNames(logic, this); IProcessDataDescription processDataDescription = ProcessDataDescription.GetDisplayNames(logic, this); string json = JsonSerializer.Serialize(processDataDescription, processDataDescription.GetType()); object @object = JsonSerializer.Deserialize(json); if (@object is not JsonElement jsonElement) throw new Exception(); foreach (JsonProperty jsonProperty in jsonElement.EnumerateObject()) { if (jsonProperty.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array) throw new Exception(); value = jsonProperty.Value.ToString(); if (!results.Contains(jsonProperty.Name) && pairedParameterNames.Contains(jsonProperty.Name) && (string.IsNullOrEmpty(value) || value[0] == '|')) results.Add(jsonProperty.Name); } } return results; } public List GetProcessDataDescriptions(JsonElement jsonElement) { List results; if (jsonElement.ValueKind != JsonValueKind.Array) throw new Exception(); JsonSerializerOptions jsonSerializerOptions = new() { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString }; results = JsonSerializer.Deserialize>(jsonElement.ToString(), jsonSerializerOptions); return results; } public Dictionary> GetKeyValuePairs(List processDataDescriptions) { Dictionary> results = new(); Test testKey; for (int i = 0; i < processDataDescriptions.Count; i++) { testKey = (Test)processDataDescriptions[i].Test; if (!results.ContainsKey(testKey)) results.Add(testKey, new List()); results[testKey].Add(processDataDescriptions[i]); } return results; } public Dictionary> GetKeyValuePairs(JsonElement jsonElement, List processDataDescriptions, Test test) { Dictionary> results = new(); Test testKey; if (jsonElement.ValueKind != JsonValueKind.Array) throw new Exception(); JsonElement[] jsonElements = jsonElement.EnumerateArray().ToArray(); if (processDataDescriptions.Count != jsonElements.Length) throw new Exception(); for (int i = 0; i < processDataDescriptions.Count; i++) { testKey = (Test)processDataDescriptions[i].Test; if (testKey != test) continue; foreach (JsonProperty jsonProperty in jsonElements[i].EnumerateObject()) { if (jsonProperty.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array) throw new Exception(); if (!results.ContainsKey(jsonProperty.Name)) results.Add(jsonProperty.Name, new List()); results[jsonProperty.Name].Add(jsonProperty.Value.ToString()); } } return results; } protected void VerifyProcessDataDescription(ILogic logic) { string description; bool allowNull = false; JsonElement defaultJsonElement = GetDefaultJsonElement(logic); Dictionary keyValuePairs = GetDisplayNamesJsonElement(logic); JsonProperty[] jsonProperties = defaultJsonElement.EnumerateObject().ToArray(); foreach (JsonProperty jsonProperty in jsonProperties) { if (jsonProperty.Value.ValueKind == JsonValueKind.Null && !allowNull) throw new Exception(); if (jsonProperty.Value.ValueKind is not JsonValueKind.String || !keyValuePairs.ContainsKey(jsonProperty.Name)) description = string.Empty; else description = keyValuePairs[jsonProperty.Name].Split('|')[0]; } } public List GetIProcessDataDescriptions(JsonElement jsonElement) { List results = new(); if (jsonElement.ValueKind != JsonValueKind.Array) throw new Exception(); object @object; Type type = ProcessDataDescription.GetType(); JsonElement[] jsonElements = jsonElement.EnumerateArray().ToArray(); JsonSerializerOptions jsonSerializerOptions = new() { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString }; for (int i = 0; i < jsonElements.Length; i++) { @object = JsonSerializer.Deserialize(jsonElements[i].ToString(), type, jsonSerializerOptions); if (@object is not IProcessDataDescription processDataDescription) continue; results.Add(processDataDescription); } return results; } }