using Autofac;
using FluentValidation;
using GreenTree.Nachtragsmanagement.Core;
using GreenTree.Nachtragsmanagement.Services.Appendix;
using GreenTree.Nachtragsmanagement.Services.Site;
using GreenTree.Nachtragsmanagement.Web.Models.Appendix;
using GreenTree.Nachtragsmanagement.Web.Models.Deviation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GreenTree.Nachtragsmanagement.Web.Validation.Appendix
{
    public class AppendixDataModelValidator : AbstractValidator<AppendixDataModel>
    {
        public AppendixDataModelValidator()
        {
            RuleFor(m => m.CustomNumber)
                .NotEmpty()
                    .WithMessage("Nummer wird benötigt")
                .MaximumLength(10)
                    .WithMessage("Muss unter 10 Zeichen sein");

            RuleFor(m => m)
                .Must(m => CustomNumberDoesNotExistInSite(m))
                    .WithMessage("Nachtragsnummer in Baustelle bereits vorhanden.");

            RuleFor(m => m.Description)
                .NotEmpty()
                    .WithMessage("Beschreibung wird benötigt");

            RuleFor(m => m.OfferingDate)
                .NotEmpty()
                    .WithMessage("Einreichdatum wird benötigt");
        }

        private bool CustomNumberDoesNotExistInSite(AppendixDataModel model)
        {
            var siteService = Singleton<IContainer>.Instance.Resolve<ISiteService>();

            if (model == null) return false;

            if (!model.SiteId.HasValue) return false;

            var existingAppendix =
                siteService.GetSiteById(model.SiteId.Value).Appendices
                    .FirstOrDefault(a => a.CustomNumber == model.CustomNumber);

            if (existingAppendix != null && existingAppendix.Id == model.Id) return true;

            if (existingAppendix != null && existingAppendix.Id != model.Id) return false;

            if (existingAppendix == null) return true;

            return false;
        }
    }
}