TarifasANEEL/Utilities/TarifaHelper.cs

125 lines
4.4 KiB
C#

using System.Data;
using System.Text.Json.Nodes;
using TarifasANEEL.Models;
using TarifasANEEL.Services;
namespace TarifasANEEL.Utilities
{
public static class TarifaHelper
{
private static readonly Dictionary<string, Func<JsonNode, string, string>> ProfileBuilders = new()
{
["SCEE"] = (record, modality) => $"SCEE - {modality.ToUpper()}",
["APE"] = (record, modality) => $"{modality.ToUpper()} APE"
};
public static Dictionary<int, Dictionary<string, Dictionary<string, Dictionary<string, Tarifa>>>> FormatData(JsonNode records)
{
var formattedData = new Dictionary<int, Dictionary<string, Dictionary<string, Dictionary<string, Tarifa>>>>();
foreach (var record in records.AsArray())
{
if (record == null) continue;
var tempTarifa = Tarifa.FromRecord(record);
var idDist = tempTarifa.ID_dist;
if (idDist == 0) continue;
var grupo = tempTarifa.Grupo;
var perfil = tempTarifa.Perfil;
var ciclo = tempTarifa.Ciclo;
// Get or create the Tarifa object
var tarifa = formattedData
.GetOrAdd(idDist)
.GetOrAdd(grupo)
.GetOrAdd(perfil)
.GetOrAdd(ciclo, () => tempTarifa);
// Update the component values based on the record
tarifa.UpdateComponentValue(record);
}
// Filter out Tarifas with all zero/null/empty values
foreach (var distKvp in formattedData.ToList())
{
foreach (var grupoKvp in distKvp.Value.ToList())
{
foreach (var perfilKvp in grupoKvp.Value.ToList())
{
foreach (var cicloKvp in perfilKvp.Value.ToList())
{
if (cicloKvp.Value.HasAllEmptyValues())
{
perfilKvp.Value.Remove(cicloKvp.Key);
}
}
if (perfilKvp.Value.Count == 0)
{
grupoKvp.Value.Remove(perfilKvp.Key);
}
}
if (grupoKvp.Value.Count == 0)
{
distKvp.Value.Remove(grupoKvp.Key);
}
}
if (distKvp.Value.Count == 0)
{
formattedData.Remove(distKvp.Key);
}
}
return formattedData;
}
public static string BuildProfileName(JsonNode record, string modality)
{
var consumerDetail = record["DscDetalheConsumidor"]!.ToString();
string profile = ProfileBuilders.TryGetValue(consumerDetail, out var builder)
? builder(record, modality)
: string.Join('_', new[] {
modality.ToUpper(),
consumerDetail.ToUpper()
}.Where(x => !string.IsNullOrEmpty(x)));
return string.Join('_', new[] {
profile,
record["DscClasseConsumidor"]!.ToString().ToUpper(),
record["DscSubClasseConsumidor"]!.ToString().ToUpper()
}.Where(x => !string.IsNullOrEmpty(x)));
}
public static string ParseResolution(JsonNode record)
{
return record["DscResolucaoHomologatoria"]!.ToString()
.Split(' ')[3]
.Replace(".", "")
.Replace(",", "");
}
}
// Add this extension method to help with dictionary operations
public static class DictionaryExtensions
{
public static TValue GetOrAdd<TKey, TValue>(
this Dictionary<TKey, TValue> dict,
TKey key,
Func<TValue>? valueFactory = null) where TKey : notnull
{
if (!dict.TryGetValue(key, out var value))
{
value = valueFactory != null
? valueFactory()
: (TValue)Activator.CreateInstance(typeof(TValue))!;
dict[key] = value;
}
return value;
}
}
}