using System.Linq; using System.Web.Mvc; using Portoa.Persistence; using Portoa.Util; using Portoa.Web.Controllers; using Portoa.Web.Util; using VideoGameQuotes.Api; using VideoGameQuotes.Web.Models; using VideoGameQuotes.Web.Security; using VideoGameQuotes.Web.Services; namespace VideoGameQuotes.Web.Controllers { public class PublisherController : Controller { private readonly IPublisherService publisherService; public PublisherController(IPublisherService publisherService) { this.publisherService = publisherService; } protected new ActionResult Json(object data) { return this.SerializeToJson(data); } [HttpPost, VerifyUser(Group = UserGroup.Admin)] public ActionResult Delete(int id) { if (id < 1) { return Json(this.CreateJsonResponse("Invalid ID")); } try { var publisher = publisherService.FindById(id); var games = publisherService.GetGamesForPublisher(publisher); if (games.Any()) { return Json(this.CreateJsonErrorResponse( string.Format("The following games are still using this publisher: {0}", games.Implode(game => game.Name, ", ")) )); } } catch (EntityNotFoundException) { return Json(this.CreateJsonErrorResponse("No publisher exists for ID " + id)); } publisherService.Delete(id); return Json(this.CreateJsonResponse()); } [HttpPost, VerifyUser(Group = UserGroup.Admin)] public ActionResult Edit(EditPublisherModel model) { if (model.PublisherId < 1) { ModelState.AddModelError("PublisherId", "Invalid publisher ID"); } if (!ModelState.IsValid) { return Json(this.CreateJsonErrorResponse("Some errors occurred")); } var publisher = publisherService.FindById(model.PublisherId); publisher.Name = model.PublisherName; publisher.Website = model.PublisherWebsite; publisher = publisherService.Save(publisher); return Json(this.CreateJsonResponse(data: publisher.ToDto())); } [HttpPost, VerifyUser] public ActionResult Create(EditPublisherModel model) { if (!ModelState.IsValid) { return Json(this.CreateJsonErrorResponse("Some errors occurred.")); } if (publisherService.FindByName(model.PublisherName) != null) { return Json(this.CreateJsonResponse("A publisher with that name already exists.")); } var publisher = publisherService.Save(new Publisher { Name = model.PublisherName, Website = model.PublisherWebsite }); return Json(this.CreateJsonResponse(data: publisher.ToDto())); } } }