using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using InventoryTraker.Web.ActionResults;

namespace InventoryTraker.Web.Controllers
{
	public abstract class ControllerBase : Controller
	{
		public BetterJsonResult<T> BetterJson<T>(T model)
		{
			return new BetterJsonResult<T> {Data = model};
		}

		protected 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;
		}
	}
}