using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using AutoMapper;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.Utility;

namespace MileageTraker.Web.ViewModels.CreateLog
{
	public class ImportLogViewModel
	{
		[Required(ErrorMessage = "Required")]
		[StringLength(6, MinimumLength = 4, ErrorMessage = "Must be a 4 digit number")]
		[Display(Name = "Vehicle ID")]
		[HiddenInput]
		public string VehicleId { get; set; }

		[Required(ErrorMessage = "Required")]
		[Range(1, 500000, ErrorMessage = "Between 1 and 500k")]
		[Display(Name = "End Odometer")]
		[HiddenInput]
		public string EndOdometer { get; set; }

		[Required(ErrorMessage = "Required")]
		[MileageLogTypeValid(ErrorMessage = "Invalid Log Type")]
		[Display(Name = "Type")]
		[HiddenInput]
		public string LogType { get; set; }

		[Required(ErrorMessage = "Required")]
		[Display(Name = "Destination City")]
		[StringLength(64, MinimumLength = 3, ErrorMessage = "Minimum 3 characters")]
		[HiddenInput]
		public string CityName { get; set; }

		[Required(ErrorMessage = "Required")]
		[Display(Name = "Purpose")]
		[HiddenInput]
		public string Purpose { get; set; }

		[StringLength(64, MinimumLength = 3, ErrorMessage = "Minimum 3 characters")]
		[HiddenInput]
		public string Notes { get; set; }

		[Display(Name = "Gas Purchased")]
		[HiddenInput]
		public string GasPurchased { get; set; }

		[Required(ErrorMessage = "Required")]
		[DataType(DataType.Date)]
		[DenyFutureDate(ErrorMessage = "Future date")]
		[DenyPreviousMonthDate(ErrorMessage = "Previous Month")]
		[HiddenInput]
		public string Date { get; set; }

		static ImportLogViewModel()
		{
			Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
			Mapper.CreateMap<string, double>().ConvertUsing(Convert.ToDouble);
			Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
			Mapper.CreateMap<ImportLogViewModel, CreateLogViewModel>()
				  .ForMember(u => u.LogType, opt => opt.Ignore())
				  .ForMember(u => u.Purpose, opt => opt.Ignore());
			Mapper.CreateMap<ImportLogViewModel, Models.Log>()
				  .ForMember(u => u.Purpose, opt => opt.Ignore())
			      .ForMember(dest => dest.GasPurchased,
			                 opt =>
			                 opt.ResolveUsing(vm => 
								 string.IsNullOrEmpty(vm.GasPurchased) 
								 ? 0 
								 : Math.Round(Double.Parse(vm.GasPurchased), 3)));
		}
		
		public CreateLogViewModel GetCreateLogViewModel()
		{
			var log = new CreateLogViewModel();
			Mapper.Map(this, log);
			return log;
		}

		public Models.Log GetLog()
		{
			var log = new Models.Log();
			Mapper.Map(this, log);
			return log;
		}

		public override string ToString()
		{
			return string.Format(
				"vehicle: {0}, odo: {1}, type: {2}, city: {3}, gas: {4}, purpose: {5}, date: {6}",
				VehicleId, EndOdometer, LogType, CityName, GasPurchased, Purpose, Date);
		}
	}
}