using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Text; using System.IO; using Serilog; using LCU.Api.Internal.MaidBotApi.DataAccesses; using LCU.Api.Internal.MaidBotLib.Models; using LCU.Library.Internal.Exceptions; using LCU.Shared.Common.NotificationApiLib.Models; using LCU.Api.Internal.MaidBotApi.Configurations; namespace LCU.Api.Internal.MaidBotApi.Services; public class NotificationsApiService : INotificationsApiService { private readonly ApiConfiguration _apiConfiguration; private readonly INotificationsApiDao _notificationsApiDao; private const string TableRowsTag = "{TableRows}"; private const string ApplicationTag = "{Application}"; private const string LevelTag = "{Level}"; public NotificationsApiService(ApiConfiguration apiConfiguration, INotificationsApiDao notificationsApiDao) { _apiConfiguration = apiConfiguration; _notificationsApiDao = notificationsApiDao; } public async Task SendNotificationAsync(LoggingMatrix loggingMatrix, List eventLogs) { try { var emailRequest = new EmailRequest { Recipient = new List { loggingMatrix.Email }, Subject = $"{loggingMatrix.Application} - {loggingMatrix.Level}", Body = CreateEmailBody(loggingMatrix, eventLogs) }; await _notificationsApiDao.SendEmailRequest(emailRequest); } catch (Exception exception) { var message = $"Failure to Send Maidbot Email."; Log.Error(exception, message); throw new ServiceException($"{message} Exception Message: {exception.Message}"); } } public string CreateEmailBody(LoggingMatrix loggingMatrix, List eventLogs) { var errorRows = new StringBuilder(); foreach(var eventLog in eventLogs) { errorRows.Append(CreateEventLogRow(eventLog)); } var logEmailTemplateReader = new StreamReader(_apiConfiguration.LogEmailTemplate); string logEmailTemplateOutput = logEmailTemplateReader.ReadToEnd(); logEmailTemplateOutput = logEmailTemplateOutput.Replace(TableRowsTag, errorRows.ToString()); logEmailTemplateOutput = logEmailTemplateOutput.Replace(ApplicationTag, loggingMatrix.Level); return logEmailTemplateOutput.Replace(LevelTag, loggingMatrix.Application); } public string CreateEventLogRow(EventLog eventLog) { var errorRowReader = new StreamReader(_apiConfiguration.LogEmailRowTemplate); string errorRowOutput = errorRowReader.ReadToEnd(); foreach (var property in eventLog.GetType().GetProperties()) { string value = property.GetValue(eventLog) == null ? string.Empty : property.GetValue(eventLog).ToString(); errorRowOutput = errorRowOutput.Replace($"{{{property.Name}}}", value); } return errorRowOutput; } }