using Exam.Infrastructure.Extensions;
using Exam.Infrastructure.Validation.Validation;
using FluentValidation;
using Hotline.Exams.Sourcewares;
using Hotline.Exams.Validate;
using Hotline.Repository.SqlSugar.Exam.Interfaces.Sourcewares;
using Hotline.Repository.SqlSugar.Exam.Validate;

namespace Exam.Repository.Sqlsugar.Validators.Sourcewares
{
    public class SourcewareValidator:BaseValidator<ExamSourceware>
    {
        private readonly ISourcewareRepository _sourcewareRepository;
        public SourcewareValidator(ISourcewareRepository sourcewareRepository)
        {
            _sourcewareRepository = sourcewareRepository;

            RuleSet(ValidatorTypeConstants.Create, () =>
            {
                BaseValidateRule();

                ValidateRuleWithAdd();
            });

            RuleSet(ValidatorTypeConstants.Modify, () =>
            {
                BaseValidateRule();

                ValidateRuleWithModify();
            });
        }

        protected override void BaseValidateRule()
        {
            base.BaseValidateRule();
            RuleFor(m => m.Name).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamSourceware.Name))));            
        }

        protected override void ValidateRuleWithAdd()
        {
            base.ValidateRuleWithAdd();
            RuleFor(m => m.CreationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamSourceware.CreationTime))));
            RuleFor(m => m.Name).Must(v => !_sourcewareRepository.Queryable().Any(x => x.Name == v)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamSourceware.Name))));
        }

        protected override void ValidateRuleWithModify()
        {
            base.ValidateRuleWithModify();
            RuleFor(m => m.LastModificationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamSourceware.LastModificationTime))));
            RuleFor(m => m.Name).Must((t,v) => !_sourcewareRepository.Queryable().Any(x => x.Name == v && t.Id != x.Id)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamSourceware.Name))));
        }

    }
}
