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

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

        // The global geocoding service
        private readonly IGeocodingService _geocodingService;

        #endregion

        #region Ctor

        /// <summary>
        /// Initializes a new instance of the SupplierValidator class
        /// </summary>
        /// <param name="geocodingService">Global geocoding service.</param>
        public SupplierValidator(IGeocodingService geocodingService)
        {
            _geocodingService = geocodingService;

            RuleFor(m => m.Name)
                .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 SupplierModel;

                    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;
                    }
                });

            RuleFor(x => x.PhoneFirst)
                .NotNull()
                .DependentRules(() => 
                {
                    RuleFor(x => x.MailFirst)
                        .NotNull();
                });
        }

        #endregion
    }
}
