using Exam.Infrastructure.Extensions;
using Exam.Infrastructure.Validation.Validation;
using FluentValidation;
using Hotline.Repository.SqlSugar.Exam.Interfaces.Questions;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using Hotline.Exams.Questions;
using Hotline.Exams.Validate;
using Hotline.Repository.SqlSugar.Exam.Validate;

namespace Exam.Repository.Sqlsugar.Validators.Questions
{
    public class QuestionValidator : BaseValidator<ExamQuestion>
    {
        private readonly IQuestionRepository _questionRepository;
        public QuestionValidator(IQuestionRepository questionRepository)
        {
            _questionRepository = questionRepository;

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

                ValidateRuleWithAdd();
            });

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

                ValidateRuleWithModify();
            });
        }

        protected override void BaseValidateRule()
        {
            base.BaseValidateRule();
            RuleFor(m => m.Title).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamQuestion.Title))));
            RuleFor(m => m.DifficultyLevel).NotNull().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamQuestion.DifficultyLevel))));
            RuleFor(m => m.FormalEnable).NotNull().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamQuestion.FormalEnable))));
            RuleFor(m => m.SimulateEnable).NotNull().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamQuestion.SimulateEnable))));

        }

        protected override void ValidateRuleWithAdd()
        {
            base.ValidateRuleWithAdd();
            RuleFor(m => m.CreationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamQuestion.CreationTime))));

            RuleFor(m => m.Title).Must(v => !_questionRepository.Queryable().Any(x => x.Title == v)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamQuestion.Title))));
        }

        protected override void ValidateRuleWithModify()
        {
            base.ValidateRuleWithModify();
            RuleFor(m => m.LastModificationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamQuestion.LastModificationTime))));
            RuleFor(m => m.Title).Must((q, v, ctx) => !_questionRepository.Queryable().Where(x => x.Title ==v  && x.Id  != q.Id).Any()).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamQuestion.Title))));        }

       

    }
}
