using FluentValidation;
using GreenTree.Strohrmann.ERP.Domain.Model;
using GreenTree.Strohrmann.ERP.Services.Geolocator;
using GreenTree.Strohrmann.ERP.Web.Models.Business;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace GreenTree.Strohrmann.ERP.Web.Validators
{
	public class CustomerValidator : AbstractValidator<CustomerModel>
	{
		#region DI fields

		// The global DbContext
		private readonly ERPDbContext _eRPDbContext;

		// The global geocoding service
		private readonly IGeocodingService _geocodingService;

		#endregion

		#region Ctor

		/// <summary>
		/// Initializes a new instance of the CustomerValidator class
		/// </summary>
		/// <param name="eRPDbContext">Global DbContext.</param>
		/// <param name="geocodingService">Global geocoding service.</param>
		public CustomerValidator(
			ERPDbContext eRPDbContext,
			IGeocodingService geocodingService)
		{
			_eRPDbContext = eRPDbContext;
			_geocodingService = geocodingService;

			RuleFor(m => m.Firstname)
				.NotEmpty();

			RuleFor(m => m.Lastname)
				.NotEmpty();

			RuleFor(m => m.Address)
				.NotEmpty();

			RuleFor(m => m.ZipCode)
				.NotEmpty();

			RuleFor(m => m.Town)
				.NotEmpty();

			RuleFor(m => m.Country)
				.NotEmpty();

			RuleFor(m => m.Address)
				.Custom((a, context) =>
				{
					var model = context.InstanceToValidate as CustomerModel;

					if (model == null)
					{
						context.AddFailure("Unbekannter Fehler.");
						return;
					}

					var addressValid = _geocodingService.IsValidAddress(
						String.Format("{0} {1} {2}", model.Address, model.ZipCode, model.Town));

					if (!addressValid)
					{
						context.AddFailure("Adresse kann nicht gefunden werden. Bitte überprüfen Sie die Adresseingaben.");
						return;
					}
				});
		}

        #endregion
    }
}