using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using AutoMapper;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Utility;

namespace MileageTraker.Web
{
	public class MvcApplication : HttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			
			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = "CreateLog", action = "Index", id = UrlParameter.Optional } // Parameter defaults
				);
		}

		protected void Application_Start()
		{
			Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
 
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			Database.SetInitializer(new MileageTrakerInitializer());

			ModelMetadataProviders.Current = new CustomMetadataProvider();
		}
	}

	public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
	{
		protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
		{
			var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

			if (propertyName == null)
				return metadata;

			if (metadata.DisplayName == null)
				metadata.DisplayName = propertyName.Wordify();

			var formatHint = attributes.OfType<FormatHintAttribute>().FirstOrDefault();
			metadata.AdditionalValues.Add("FormatHint", formatHint != null ? formatHint.Text : null);
			
			var unitsAttribute = attributes.OfType<UnitsAttribute>().FirstOrDefault();
			metadata.AdditionalValues.Add("Units", unitsAttribute != null ? unitsAttribute.Text : null);

			var inputSizeAttribute = attributes.OfType<InputSizeAttribute>().FirstOrDefault();
			metadata.AdditionalValues.Add("InputSize", inputSizeAttribute != null ? inputSizeAttribute.ClassName : null);

			var editLabelAttribute = attributes.OfType<NoEditLabelAttribute>().FirstOrDefault();
			metadata.AdditionalValues.Add("EditLabel", editLabelAttribute == null);
			
			return metadata;
		}
	}
}