package cn.com.qmth.stmms.admin.thread;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.lock.LockService;
import cn.com.qmth.stmms.biz.mark.service.MarkService;
import cn.com.qmth.stmms.common.enums.LockType;

public class QuestionDeleteThread implements Runnable {

    protected static Logger log = LoggerFactory.getLogger(QuestionDeleteThread.class);

    private List<ExamQuestion> list;

    private MarkService markService;

    private LockService lockService;

    private Set<String> set;

    public QuestionDeleteThread(List<ExamQuestion> list, MarkService markService, LockService lockService) {
        this.list = list;
        this.markService = markService;
        this.lockService = lockService;
    }

    @Override
    public void run() {
        if (list == null || list.isEmpty()) {
            return;
        }
        int examId = list.get(0).getExamId();
        String subjectCode = list.get(0).getSubjectCode();
        set = new HashSet<String>();
        for (ExamQuestion question : list) {
            set.add(getKey(question));
        }
        try {
            lockService.waitlock(LockType.EXAM_SUBJECT, examId, subjectCode);
            log.info("delete question examId=" + examId + " subjectCode=" + subjectCode);
            markService.deleteByQuestion(list);
        } catch (Exception e) {
            log.error("delete group error", e);
        } finally {
            lockService.unlock(LockType.EXAM_SUBJECT, examId, subjectCode);
            for (String key : set) {
                String s[] = key.split("\t");
                Integer mainNumber = Integer.parseInt(s[3]);
                String subNumber = StringUtils.trimToEmpty(s[4]);
                lockService.unlock(LockType.QUESTION_DELETE, examId, subjectCode, mainNumber, subNumber);
            }
        }
    }

    protected String getKey(ExamQuestion question) {
        return question.getExamId() + "\t" + question.getSubjectCode() + "\t" + question.isObjective() + "\t"
                + question.getMainNumber() + "\t" + question.getSubNumber();
    }
}
