using GerbilManagerWebAPI.Models; using GerbilManagerWebAPI.DAL; using GerbilManagerWebAPI.Dtos; using GerbilManagerWebAPI.Converter; using Microsoft.AspNetCore.Mvc; using System.Xml; namespace GerbilManagerWebAPI.Controllers { [ApiController] [Route("litters")] public class LittersController : ControllerBase { private readonly UnitOfWork unitOfWork; public LittersController(UnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } //GET /gerbils [HttpGet] public IEnumerable GetLitters() { var items = unitOfWork.LitterRepository.Get().Select( litter => litter.AsDto()); return items; } //GET /gerbils [HttpGet("{id}")] public ActionResult GetLitter(Guid id) { var item = unitOfWork.LitterRepository.GetByID(id).AsDto(); if(item is null) { return NotFound(); } return item; } [HttpPost()] public ActionResult CreateLitter(CreateLitterDto dto) { //Sanity check if father is male and mother is female var father = this.unitOfWork.GerbilRepository.GetByID(dto.Father ?? Guid.Empty); var mother = this.unitOfWork.GerbilRepository.GetByID(dto.Mother ?? Guid.Empty); if(father?.Gender == Gender.female || mother?.Gender == Gender.male) { return BadRequest($"The mothers gender is {mother?.Gender.ToString() ?? "unknown"} and the fathers {father?.Gender.ToString() ?? "unknown"}."); } Litter litter = new Litter{ Id = Guid.NewGuid(), Date = dto.Date, Father = this.unitOfWork.GerbilRepository.GetByID(dto.Father ?? Guid.Empty), Mother = this.unitOfWork.GerbilRepository.GetByID(dto.Mother ?? Guid.Empty), Name = dto.Name, Strength = dto.Strength }; this.unitOfWork.LitterRepository.Insert(litter); this.unitOfWork.Save(); return CreatedAtAction(nameof(GetLitter), new { id = litter.Id}, litter.AsDto()); } [HttpPut("{id}")] public ActionResult UpdateLitter(Guid id, UpdateLitterDto litterDto) { var existingItem = unitOfWork.LitterRepository.GetByID(id); if(existingItem is null) { return NotFound(); } Litter updatedLitter = existingItem with{ Date = litterDto.Date ?? DateTime.Now, Strength = litterDto.Strength, Father = this.unitOfWork.GerbilRepository.GetByID(litterDto.Father ?? Guid.Empty), Mother = this.unitOfWork.GerbilRepository.GetByID(litterDto.Mother ?? Guid.Empty), Name = litterDto.Name }; unitOfWork.LitterRepository.Update(updatedLitter); this.unitOfWork.Save(); return NoContent(); } [HttpDelete("{id}")] public ActionResult DeleteLitter(Guid id) { var existingLitter = unitOfWork.LitterRepository.GetByID(id); if(existingLitter is null) { return NotFound(); } unitOfWork.LitterRepository.Delete(existingLitter); this.unitOfWork.Save(); return NoContent(); } } }