using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using InventoryTraker.Web.ActionResults;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Utilities;
using NLog;

namespace InventoryTraker.Web.Controllers
{
	public abstract class ControllerBase : Controller
	{
		protected override void OnException(ExceptionContext ctx)
		{
			if (ctx?.Exception != null)
			{
				var loggerName = ctx.GetLoggerName();

				LogManager.GetLogger(loggerName).Error(ctx.Exception);
			}

			base.OnException(ctx);
		}

		protected BetterJsonResult<T> BetterJson<T>(T model)
		{
			return new BetterJsonResult<T> {Data = model};
		}

		private string[] GetModelStateErrorList()
		{
			var errorList =
				from kvp in ModelState
				where kvp.Value.Errors.Any()
				let errors = string.Join(", ", kvp.Value.Errors.Select(e => e.ErrorMessage))
				let msg = kvp.Key + ": " + errors
				select msg;
			return errorList.ToArray();
		}

		protected JsonResult GetModelStateErrorListJson()
		{
			return GetErrorListJson(GetModelStateErrorList());
		}

		protected JsonResult GetErrorListJson(params string[] errors)
		{
			var betterJsonResult = new BetterJsonResult();
			foreach (var err in errors)
				betterJsonResult.AddError(err);
			return betterJsonResult;
		}
	}
}