using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using gehGassi.Core.Interfaces; using gehGassi.Domain.Common; using gehGassi.Domain.Dogs; using Microsoft.EntityFrameworkCore; namespace gehGassi.Core.Services { /// /// Service die Verwaltung von Relationen zwischen Entitäten ermöglicht /// public class AppUserRelationService : ServiceBase, IAppUserRelationService { /// /// Erstellt eine Instanz /// /// Instanz eines IUnitOfWork public AppUserRelationService(IUnitOfWork unitOfWork) : base(unitOfWork) { } /// /// Fügt eine Relation hinzu wenn diese nicht bereits existiert. /// Dabei werden beide Richtungen geprüft. /// /// Id der ersten Entität /// Id der zweiten Entität /// Benutzer der die Änderung vorgenommen hat /// Neue Relation oder gefundene Relation public async Task AddIfNotExistsAsync(string leftId, string rightId, string userName) { var query = Repository.Query(c => (c.LeftId == leftId && c.RightId == rightId) || (c.LeftId == rightId && c.RightId == leftId)); var found = await query.FirstOrDefaultAsync().ConfigureAwait(false); if (found == null) { found = new AppUserRelation { LeftId = leftId, RightId = rightId, Created = DateTime.Now }; Repository.Add(found); await CommitAsync(userName); } return found; } /// /// Setzen einer Relation auf gelöscht - einseitig. /// Für den Initiator wird "gelöscht" gesetzt. /// Der Initiator wird dabei aber in Left und Right gesucht. /// /// Id des Initiators /// Id der anderen Entität /// Benutzer der die Änderung vorgenommen hat /// true wenn auf gelöscht gesetzt, false sonst public async Task DeleteAsync(string initiatorId, string otherId, string userName) { var query = Repository.Query(c => (c.LeftId == initiatorId && c.RightId == otherId) || (c.LeftId == otherId && c.RightId == initiatorId)); var found = await query.FirstOrDefaultAsync().ConfigureAwait(false); if (found != null) { if (found.LeftId == initiatorId) found.LeftDeleted = true; else found.RightDeleted = true; } return false; } /// /// Gibt eine Liste von Relationszielen zurück, zu welcher der Initiator eine Beziehung hat /// /// Id des Initiators /// Sollen gelöschte inkludiert werden? /// Liste von Relationszielen public async Task> GetRelations(string initiatorId, bool includeDeleted = false) { var resultList = new List(); var query = Repository.Query(c => c.LeftId == initiatorId || c.RightId == initiatorId ); if (includeDeleted == false) query = query.Where(c => c.RightDeleted == false && c.LeftDeleted == false); var items = await query.ToListAsync().ConfigureAwait(false); foreach (var item in items) { if(item.LeftId == initiatorId) resultList.Add(new AppUserRelationTarget(){Id = item.Id, TargetId = item.RightId}); else resultList.Add(new AppUserRelationTarget() { Id = item.Id, TargetId = item.LeftId}); } return resultList; } } }