using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System.Collections.Generic; using System.Threading.Tasks; using zero.Core.Entities; using zero.Core.Identity; using zero.Core.Mapper; using zero.Core.Options; using zero.Web.Filters; using zero.Web.Models; namespace zero.Web.Controllers { [ZeroAuthorize] [CanEdit] [AddToken] [BackofficeGenericController] public abstract class BackofficeController : Controller, ISupportsGenericsController { IMapper _mapper; IZeroOptions _options; protected IMapper Mapper => _mapper ?? (_mapper = HttpContext?.RequestServices?.GetService()); protected IZeroOptions Options => _options ?? (_options = HttpContext?.RequestServices?.GetService()); static JsonSerializerSettings JsonSettings; static JsonSerializerSettings TypedJsonSettings; static BackofficeController() { JsonSettings = new BackofficeJsonSerlializerSettings(false); TypedJsonSettings = new BackofficeJsonSerlializerSettings(true); } /// /// Creates a Microsoft.AspNetCore.Mvc.JsonResult object that serializes the specified data object to JSON. /// public override JsonResult Json(object data) => Json(data, false); /// /// Creates a Microsoft.AspNetCore.Mvc.JsonResult object that serializes the specified data object to JSON. /// public JsonResult Json(object data, bool typed) => Json(data, typed ? TypedJsonSettings : JsonSettings); /// /// Creates an edit model with appropriate options and permissions /// public JsonResult JsonEdit(T data) => JsonEdit(data, false); /// /// Creates an edit model with appropriate options and permissions /// public JsonResult JsonEdit(T data, bool typed) { return Json(new EditModel() { Entity = data, CanEdit = true }, typed); } protected async Task As(T model) where TTarget : class, new() where T : IZeroEntity { if (model == null) { return new StatusCodeResult(404); } if (Mapper == null) { // TODO show error with help on how to inject mapper in constructor + base constructor } TTarget result = await Mapper.Map(model); if (result is ObsoleteEditModel) { ObsoleteEditModel editModel = result as ObsoleteEditModel; //model.CanEdit = } return Json(result); } protected async Task As(IEnumerable model) where TTarget : class, new() where T : IZeroEntity { if (model == null) { return new StatusCodeResult(404); } return Json(await Mapper.Map(model)); } protected async Task As(ListResult model) where TTarget : class, new() where T : IZeroEntity { if (model == null) { return new StatusCodeResult(404); } return Json(await Mapper.Map(model)); } protected async Task As(EntityResult model) where TTarget : class, new() where T : IZeroEntity { if (model == null) { return new StatusCodeResult(404); } return Json(await Mapper.Map(model)); } protected async Task Map(T model) where TTarget : class, new() { return await Mapper.Map(model); } } }