using System.Web.Mvc; using Portoa.Persistence; 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 CategoryController : Controller { private readonly ICategoryService categoryService; public CategoryController(ICategoryService categoryService) { this.categoryService = categoryService; } 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 category = categoryService.FindById(id); var numQuotes = categoryService.GetQuotesForCategory(category); if (numQuotes > 0) { return Json(this.CreateJsonErrorResponse( string.Format("There are {0} quotes that are still using this category", numQuotes) )); } } catch (EntityNotFoundException) { return Json(this.CreateJsonErrorResponse("No category exists for ID " + id)); } categoryService.Delete(id); return Json(this.CreateJsonResponse()); } [HttpPost, VerifyUser(Group = UserGroup.Admin)] public ActionResult Edit(EditCategoryModel model) { if (model.CategoryId < 1) { ModelState.AddModelError("CategoryId", "Invalid category ID"); } if (!ModelState.IsValid) { return Json(this.CreateJsonErrorResponse("Some errors occurred")); } try { var category = categoryService.FindById(model.CategoryId); if (categoryService.FindByName(model.CategoryName) != null) { return Json(this.CreateJsonErrorResponse("A category already exists for that name")); } category.Name = model.CategoryName; category = categoryService.Save(category); return Json(this.CreateJsonResponse(data: category.ToDto())); } catch (EntityNotFoundException) { return Json(this.CreateJsonErrorResponse("No category exists for ID " + model.CategoryId)); } } [HttpPost, VerifyUser] public ActionResult Create(EditCategoryModel model) { if (!ModelState.IsValid) { return Json(this.CreateJsonErrorResponse("Some errors occurred.")); } if (categoryService.FindByName(model.CategoryName) != null) { return Json(this.CreateJsonErrorResponse("A category already exists for that name")); } var category = categoryService.Save(new Category { Name = model.CategoryName }); return Json(this.CreateJsonResponse(data: category.ToDto())); } } }