using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using MileageTraker.Web.DAL;

namespace MileageTraker.Web.Models
{
	public class Log : IValidatableObject
	{
		[Key]
		public int LogId { get; set; }

		[Required]
		[StringLength(6, MinimumLength = 4, ErrorMessage = "Enter 4 digit number")]
		[RegularExpression(@"\d+", ErrorMessage = "Enter only numbers")]
		public string VehicleId { get; set; }

		[Required]
		[Range(1, 500000, ErrorMessage = "Between 1 and 500k")]
		public int EndOdometer { get; set; }

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

		[Required]
		public virtual User User { get; set; }

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

		public virtual PurposeType Purpose { get; set; }

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

		[Range(0, 50)]
		public double GasPurchased { get; set; }

		[Required]
		[DataType(DataType.Date)]
		public DateTime Date { get; set; }

		[Display(Name = "Time Created")]
		[DisplayFormat(DataFormatString = @"{0:MM/dd/yyyy h:mm tt}")]
		[HiddenInput]
		public DateTime Created { get; set; }

		/// <summary>
		/// url route that was used to create this instance, ie 'CreateLog\Confirm' or 'Logs\Create'
		/// </summary>
		public string Source { get; set; }

		public string UserHostAddress { get; set; }

		public string UserAgent { get; set; }

		[HiddenInput(DisplayValue = false)]
		public int? VehiclePreviousLogId { get; set; }

		[HiddenInput(DisplayValue = false)]
		public virtual Log VehiclePreviousLog { get; set; }

		public Log()
		{
			LogType = new MileageLogTypeWrapper();
		}

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

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

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