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

namespace GreenTree.Nachtragsmanagement.Web.Validation.Config
{
    public class ConfigItemDataModelValidator : AbstractValidator<ConfigItemDataModel>
    {
        public ConfigItemDataModelValidator()
        {
            RuleFor(m => m.Name)
                .NotEmpty()
                    .WithMessage("Ein Name wird benötigt");

            RuleFor(m => m.TypeFullName)
                .NotEmpty()
                    .WithMessage("Der Wertetyp wird benötigt");

            RuleFor(m => m)
                .Must(m => NameDoesNotExist(m))
                    .WithMessage("Ein Konfigurationselement mit diesem Namen existiert bereits.");
        }

        private bool NameDoesNotExist(ConfigItemDataModel model)
        {
            var configService = Singleton<IContainer>.Instance.Resolve<IConfigurationService>();

            if (model == null) return false;

            var existingConfigItem = configService.GetConfigItemByName(model.Name);

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

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

            if (existingConfigItem == null) return true;

            return false;
        }
    }
}