using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using AutoMapper;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.ViewModels.Log;

namespace MileageTraker.Web.ViewModels.FuelLog
{
	public class FuelLogViewModel
	{
		[HiddenInput(DisplayValue = false)]
		public int FuelLogId { get; set; }

		[Required]
		[DataType(DataType.Date)]
		[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
		public DateTime Date { get; set; }

		[Required]
		[StringLength(128)]
		[Display(Name = "Driver Name")]
		public string DriverFullName { get; set; }

		[Required]
		[Display(Name = "Tag#")]
		public string TagNumber { get; set; }

		[HiddenInput(DisplayValue = false)]
		public string VehicleId { get; set; }

		[Required]
		public int Odometer { get; set; }

		[StringLength(64)]
		[Display(Name = "City Name")]
		public string CityName { get; set; }

		[Display(Name = "MPG")]
		public double MPG { get; set; }

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

		[Required]
		[Display(Name = "Total Price")]
		[Currency]
		public decimal TotalPrice { get; set; }

		// Matched log
		[HiddenInput(DisplayValue = false)]
		public int? LogId { get; set; }

		static FuelLogViewModel()
		{
			Mapper.CreateMap<FuelLogViewModel, Models.FuelLog>();
			Mapper.CreateMap<Models.FuelLog, FuelLogViewModel>()
				.ForMember(dest => dest.LogId,
			               opt => opt.ResolveUsing(
							   fl => fl.Log != null ? (int?)fl.Log.LogId : null
							   ));

			Mapper.CreateMap<FuelLogViewModel, LogViewModel>()
			      .ForMember(dest => dest.EndOdometer, opt => opt.MapFrom(src => src.Odometer))
			      .ForMember(dest => dest.CityName, opt => opt.MapFrom(src => src.CityName))
			      .ForMember(dest => dest.GasPurchased, opt => opt.MapFrom(src => src.GasPurchased))
				  .ForMember(dest => dest.UserFullName, opt => opt.MapFrom(src => src.DriverFullName))
				  .ForMember(dest => dest.VehicleId, opt => opt.MapFrom(src => src.VehicleId))
				  .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.Date));
		}

		public FuelLogViewModel(Models.FuelLog fuelLog)
		{
			Mapper.Map(fuelLog, this);
		}

		public FuelLogViewModel()
		{
		}

		public LogViewModel GetLogViewModel()
		{
			var logViewModel = new LogViewModel();
			Mapper.Map(this, logViewModel);
			return logViewModel;
		}
	}
}