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

namespace GreenTree.Nachtragsmanagement.Web.Validation.Site
{
    public class SiteDataModelValidator : AbstractValidator<SiteDataModel>
    {
        public SiteDataModelValidator()
        {
            RuleFor(m => m.CustomNumber)
                .NotEmpty()
                    .WithMessage("Kostenstelle wird benötigt");

            RuleFor(m => m)
                .Must(m => CustomNumberDoesNotExist(m))
                    .WithMessage("Kostenstelle bereits vorhanden.");

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

            RuleFor(m => m.Start)
                .NotEmpty()
                    .WithMessage("Ein Startdatum wird benötigt");

            RuleFor(m => m.UserValues)
                .Must(r => r.Count > 0)
                    .WithMessage("Mind. ein Bearbeiter muss ausgewählt werden");
        }

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

            if (model == null) return false;

            var existingSiteById = siteService.GetSiteById(model.Id);

            if (existingSiteById != null) return true;

            var existingSiteByCustomNumber = siteService.GetSiteByCustomNumber(model.CustomNumber);

            if (existingSiteByCustomNumber == null) return true;

            return false;
        }
    }
}