using Microsoft.EntityFrameworkCore; using RMuseum.DbContext; using RMuseum.Models.Notification; using RSecurityBackend.Models.Generic; using System; using System.Linq; using System.Threading.Tasks; namespace RMuseum.Services.Implementation { /// /// Internal messaging system implementation /// public class RNotificationService : IRNotificationService { /// /// Add Notification /// /// /// /// /// public async Task> PushNotification(Guid userId, string subject, string htmlText) { try { RUserNotification notification = new RUserNotification() { UserId = userId, DateTime = DateTime.Now, Status = NotificationStatus.Unread, Subject = subject, HtmlText = htmlText }; _context.Notifications.Add(notification); await _context.SaveChangesAsync(); return new RServiceResult(notification); } catch (Exception exp) { return new RServiceResult(null, exp.ToString()); } } /// /// Switch Notification Status /// /// /// updated notification object public async Task> SwitchNotificationStatus(Guid notificationId) { try { RUserNotification notification = await _context.Notifications.Where(n => n.Id == notificationId).SingleAsync(); notification.Status = notification.Status == NotificationStatus.Unread ? NotificationStatus.Read : NotificationStatus.Unread; _context.Notifications.Update(notification); await _context.SaveChangesAsync(); return new RServiceResult(notification); } catch (Exception exp) { return new RServiceResult(null, exp.ToString()); } } /// /// Delete Notification /// /// /// public async Task> DeleteNotification(Guid notificationId) { try { RUserNotification notification = await _context.Notifications.Where(n => n.Id == notificationId).SingleAsync(); _context.Notifications.Remove(notification); await _context.SaveChangesAsync(); return new RServiceResult(true); } catch (Exception exp) { return new RServiceResult(false, exp.ToString()); } } /// /// Get User Notifications /// /// /// public async Task> GetUserNotifications(Guid userId) { try { return new RServiceResult ( await _context.Notifications .Where(n => n.UserId == userId) .OrderByDescending(n => n.DateTime) .ToArrayAsync() ); } catch (Exception exp) { return new RServiceResult(null, exp.ToString()); } } /// /// Get Unread User Notifications Count /// /// /// public async Task> GetUnreadUserNotificationsCount(Guid userId) { try { return new RServiceResult ( await _context.Notifications .Where(n => n.UserId == userId && n.Status == NotificationStatus.Unread) .CountAsync() ); } catch (Exception exp) { return new RServiceResult(0, exp.ToString()); } } /// /// Database Contetxt /// protected readonly RMuseumDbContext _context; public RNotificationService(RMuseumDbContext context) { _context = context; } } }