using System; using System.Collections.Generic; using System.Threading.Tasks; using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Services.Cache; using IOB_UT_NEXT.Services.Networking; using IOB_UT_NEXT.Services.Data; using NLog; namespace IOB_UT_NEXT.Services.Networking { /// /// ServerCommunicationService: Orchestratore per i task del dominio SERVER (_workerTask). /// Gestisce il coordinamento tra chiamate HTTP, persistenza Redis e code di comunicazione. /// public class ServerCommunicationService { #region Public Constructors public ServerCommunicationService(IobConfTree config, RedisIobCache redisMan) { _config = config ?? throw new ArgumentNullException(nameof(config)); _redisMan = redisMan ?? throw new ArgumentNullException(nameof(redisMan)); } #endregion Public Constructors #region Public Methods /// /// Esegue una chiamata HTTP GET e deserializza il risultato. /// public async Task GetAndDeserializeAsync(string url) { try { string response = await HttpService.CallUrlAsync(url); return JsonDeserialize(response); } catch (Exception ex) { logger.Error(ex, $"[ServerComm] Error in GetAndDeserializeAsync | URL: {url}"); throw; } } /// /// Recupera dati da un URL e li salva su Redis. /// Workflow: HTTP GET -> Redis Set. /// public async Task GetAndPersistAsync(string url, string redisKey) { try { string response = await HttpService.CallUrlAsync(url); if (!string.IsNullOrEmpty(response) && !string.IsNullOrEmpty(redisKey)) { _redisMan.setRSV(redisKey, response); } return response; } catch (Exception ex) { logger.Error(ex, $"[ServerComm] Error in GetAndPersistAsync | URL: {url} | Key: {redisKey}"); throw; } } /// /// Esegue una chiamata HTTP POST e salva il risultato su Redis. /// Workflow: Serialize -> HTTP POST -> Redis Set. /// public async Task PostAndPersistAsync(string url, T payload, string redisKey) { try { string serializedPayload = JsonSerialize(payload); logger.Debug($"[ServerComm] POST to {url} | Payload: {serializedPayload}"); string response = await HttpService.CallUrlAsync(url, serializedPayload); if (!string.IsNullOrEmpty(response) && !string.IsNullOrEmpty(redisKey)) { _redisMan.setRSV(redisKey, response); logger.Info($"[ServerComm] Data persisted to Redis: {redisKey}"); } return response; } catch (Exception ex) { logger.Error(ex, $"[ServerComm] Error in PostAndPersistAsync | URL: {url} | Key: {redisKey}"); throw; } } #endregion Public Methods #region Private Fields private static readonly Logger logger = LogManager.GetCurrentClassLogger(); private readonly IobConfTree _config; private readonly RedisIobCache _redisMan; #endregion Private Fields #region Private Methods private T JsonDeserialize(string json) => IOB_UT_NEXT.Services.Data.DataSerializer.Deserialize(json); // Helper per mantenere la compatibilità con la logica di serializzazione esistente private string JsonSerialize(T obj) => IOB_UT_NEXT.Services.Data.DataSerializer.Serialize(obj); #endregion Private Methods } }