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

import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.file.service.FileService;
import cn.com.qmth.stmms.common.enums.ExamType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class ImageCheckThread implements Runnable {

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

    private AtomicBoolean running;

    private Exam exam;

    private ExamStudentService studentService;

    private FileService fileService;

    public ImageCheckThread(Exam exam, ExamStudentService studentService, FileService fileService,
            AtomicBoolean running) {
        this.exam = exam;
        this.running = running;
        this.studentService = studentService;
        this.fileService = fileService;
    }

    @Override
    public void run() {
        log.info("start check image for examId=" + exam.getId());
        try {
            int pageNumber = 1;
            int pageSize = 500;
            while (true) {
                List<ExamStudent> list = studentService
                        .findByExamIdAndUploadAndAbsent(exam.getId(), true, false, pageNumber, pageSize);
                if (list == null || list.isEmpty()) {
                    break;
                }

                for (ExamStudent student : list) {
                    checkStudent(student);
                }

                pageNumber++;
            }
        } catch (Exception e) {
            log.error("check image exception for examId=" + exam.getId(), e);
        } finally {
            running.set(false);
            log.info("finish check image for examId=" + exam.getId());
        }
    }

    private void checkStudent(ExamStudent student) {
        if (exam.getType() == ExamType.SCAN_IMAGE) {
            boolean exception = false;
            for (int i = 1; i <= student.getSheetCount(); i++) {
                if (!fileService.sheetExist(student.getExamId(), student.getExamNumber(), i)) {
                    exception = true;
                    break;
                }
            }
            for (int i = 1; i <= student.getSliceCount(); i++) {
                if (!fileService.sliceExist(student.getExamId(), student.getSecretNumber(), i)) {
                    exception = true;
                    break;
                }
            }
            record(student, exception);
        } else if (exam.getType() == ExamType.MULTI_MEDIA) {
            record(student, fileService.jsonExist(student.getExamId(), student.getSecretNumber()));
        }

    }

    private void record(ExamStudent student, boolean exception) {
        studentService.updateException(student.getId(), exception);
    }
}
