package cn.com.qmth.stmms.common.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.model.ObjectiveBlock;
import cn.com.qmth.stmms.biz.exam.model.ObjectiveQuestion;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;

public class ObjectiveBlockValidator {

    private static Logger log = LoggerFactory.getLogger(ObjectiveBlockValidator.class);

    public static boolean validate(ObjectiveBlock block, boolean withQuestion, ExamSubjectService examSubjectService) {
        if (block.getExamId() != null && StringUtils.isNotBlank(block.getSubjectCode()) && block.getNumber() != null) {
            ExamSubject subject = examSubjectService.find(block.getExamId(), block.getSubjectCode());
            if (subject != null) {
                try {
                    if (block.getNumber() > 0 && block.getOptionCount() > 0 && block.getQuestionScore() > 0) {
                        // 选做题
                        if (block.isSelective()) {
                            if (block.getSelectCount() <= 0) {
                                return false;
                            }
                        }
                        // 多选题
                        if (block.getMissScore() != null) {
                            if (block.getMissScore() > block.getQuestionScore()) {
                                return false;
                            }
                        }
                        if (withQuestion) {
                            for (ObjectiveQuestion question : block.getQuestionList()) {
                                if (!validate(question, block)) {
                                    return false;
                                }
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    log.error("ObjectiveBlockValidator-validate", e);
                }
            }
        }
        return false;
    }

    public static boolean validate(ObjectiveQuestion question, ObjectiveBlock block) {
        try {
            if (question.getNumber() > 0 && question.getAnswer().length() > 0) {
                for (int i = 0; i < question.getAnswer().length(); i++) {
                    if (((int) question.getAnswer().charAt(i) - (int) 'A') >= block.getOptionCount()) {
                        return false;
                    }
                }
                return true;
            }
        } catch (Exception e) {
            log.error("ObjectiveBlockValidator-validate", e);
        }
        return false;
    }
}
