using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using AutoMapper;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Models;
using MileageTraker.Web.Utility;

namespace MileageTraker.Web.ViewModels.Log
{
	public class LogViewModel : IValidatableObject
	{
		[HiddenInput(DisplayValue = false)]
		public int LogId { get; set; }

		[Required(ErrorMessage = "Required")]
		[Remote("Exists", "Vehicle", ErrorMessage = "ID not found")]
		[StringLength(6, MinimumLength = 4, ErrorMessage = "Must be a 4 digit number")]
		[Display(Name = "Vehicle ID")]
		[InputSize("mini")]
		[RegularExpression(@"\d+", ErrorMessage = "Must be all numbers")]
		public string VehicleId { get; set; }

		[Required(ErrorMessage = "Required")]
		[Range(1, 500000, ErrorMessage = "Between 1 and 500k")]
		[Display(Name = "End Odometer")]
		[Units("Miles")]
		[InputSize("small")]
		[RegularExpression(@"\d+", ErrorMessage = "Must be all numbers")]
		public string EndOdometer { get; set; }

		[Required(ErrorMessage = "Required")]
		[Display(Name = "Type")]
		[NoEditLabel]
		public MileageLogTypeWrapper LogType { get; set; }

		[Required(ErrorMessage = "Required")]
		[Remote("ExistsByFullName", "User", ErrorMessage = "User with this name doesn't exist")]
		[StringLength(128)]
		[Display(Name = "Driver Name")]
		[InputSize("medium")]
		public string UserFullName { get; set; }

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

		[Display(Name = "Purpose")]
		public SelectListViewModel Purpose { get; set; }

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

		[Display(Name = "Gas Purchased")]
		[DisplayFormat(DataFormatString = "{0:0.000}", ApplyFormatInEditMode = true)]
		[Units("Gallons")]
		[FormatHint("n.nnnn")]
		[InputSize("mini")]
		public string GasPurchased { get; set; }

		[Required(ErrorMessage = "Required")]
		[DataType(DataType.Date)]
		[DisplayFormat(DataFormatString = @"{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
		[DenyFutureDate(ErrorMessage = "Future date")]
		[FormatHint("mm/dd/yyyy")]
		[InputSize("small")]
		public DateTime Date { get; set; }

		[Display(Name = "Time Created")]
		[DisplayFormat(DataFormatString = @"{0:MM/dd/yyyy h:mm tt}")]
		[HiddenInput]
		public DateTime Created { get; set; }
		
		static LogViewModel()
		{
			Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
			Mapper.CreateMap<string, double>().ConvertUsing(Convert.ToDouble);
			Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
			Mapper.CreateMap<LogViewModel, Models.Log>()
					.ForMember(u => u.Purpose, opt => opt.Ignore());
			Mapper.CreateMap<Models.Log, LogViewModel>()
			      .ForMember(vm => vm.Date, opt => opt.MapFrom(m => m.Date.ToString("d")))
				  .ForMember(u => u.Purpose, opt => opt.Ignore());
		}

		public LogViewModel()
		{
			// view will crash if this isn't instantiated
			LogType = new MileageLogTypeWrapper();
			Purpose = new SelectListViewModel();
		}

		public LogViewModel(Models.Log log) : this()
		{
			Mapper.Map(log, this);
			if (log.Purpose != null)
				Purpose.Selected = log.Purpose.PurposeTypeId;
		}

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

		public void SetProperties(Models.Log log)
		{
			Mapper.DynamicMap(this, log);
		}

		public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
		{
			if (LogType == MileageLogType.GasPurchase
				&& (string.IsNullOrEmpty(GasPurchased) || double.Parse(GasPurchased) == 0))
				yield return new ValidationResult("Enter amount of gas purchased", new [] {"GasPurchased"});

			if (LogType.Value == 0)
				yield return new ValidationResult("Required", new[] { "LogType" });

			ValidationResult chronologyResult = null;
			try
			{
				using (var dataService = new DataService())
				{
					dataService.ValidateOdometerChronology(VehicleId, int.Parse(EndOdometer), Date);
				}
			}
			catch (Exception ex)
			{
				chronologyResult = new ValidationResult(ex.Message, new [] {"EndOdometer"});
			}
			if (chronologyResult != null)
				yield return chronologyResult;

			using (var dataService = new DataService())
			{
				var user = dataService.FindUserByFullName(UserFullName);
				if (user == null)
				{
					yield return new ValidationResult("User with this name doesn't exist", new[] { "UserFullName" });
				}
			}
		}
	}
}