﻿using System;
using System.Net;
using AspNetCore.Web.Models;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;

namespace AspNetCore.Web.Common
{
    /// <summary>
    /// Exception Handler for MVC (Web) Controllers. Returns an error view
    /// </summary>
    [AttributeUsage(System.AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    internal class MvcExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private readonly ILoggerFactory _factory;

        public MvcExceptionFilterAttribute(ILoggerFactory factory)
        {
            _factory = factory;
        }


        public override void OnException(ExceptionContext context)
        {
            ViewResult result = new ViewResult();

            var modelMetadataProvider = (IModelMetadataProvider)context.HttpContext.ApplicationServices.GetService(typeof(IModelMetadataProvider));
            var viewDataDictionary = new ViewDataDictionary<ErrorViewModel>(modelMetadataProvider, new ModelStateDictionary());

            viewDataDictionary.Model = new ErrorViewModel() { Exception = context.Exception };
            result.ViewData = viewDataDictionary;
            result.ViewName = "UnhandledError";
            result.StatusCode = (int)HttpStatusCode.InternalServerError;

            context.Result = result;
        }
    }
}
