using System;
using AutoMapper;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Utility;

namespace MileageTraker.Web.ViewModels.CreateLog
{
	public class ConfirmCreateLogViewModel : CreateLogViewModel
	{
		public string VehicleType { get; set; }
		public string VehicleColor { get; set; }
		public string VehicleTagNumber { get; set; }
		public string DateHowLongAgo { get; set; }
		public int? PreviousOdometer { get; set; }
		public DateTime? PreviousDate { get; set; }
		public int? Miles { get; set; }

		static ConfirmCreateLogViewModel()
		{
			Mapper.CreateMap<CreateLogViewModel, ConfirmCreateLogViewModel>()
			      .ForMember(c => c.CityName, opt => opt.AddFormatter(new TitleCaseFormatter()));
		}

		public ConfirmCreateLogViewModel(CreateLogViewModel createLogViewModel)
		{
			Mapper.Map(createLogViewModel, this);

			DateHowLongAgo = (DateTime.Today - Date).ToVerboseStringHistoric();

			using (var dataService = new DataService())
			{
				var endOdometer = int.Parse(createLogViewModel.EndOdometer);
				var date = createLogViewModel.Date;

				var previousLog = dataService.SearchPreviousLog(endOdometer, createLogViewModel.VehicleId, date, DateTime.Now);
				if (previousLog != null)
				{
					PreviousOdometer = previousLog.EndOdometer;
					PreviousDate = previousLog.Date;
					Miles = endOdometer - previousLog.EndOdometer;
				}

				var matchingCity = dataService.GetCitiesCorrected(CityName);

				if (!string.IsNullOrEmpty(matchingCity))
					CityName = matchingCity;

				var vehicle = dataService.GetVehicle(VehicleId);
				VehicleColor = vehicle.Color;
				VehicleType = vehicle.Type;
				VehicleTagNumber = vehicle.TagNumber;
			}
		}
	}
}