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

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.qmth.stmms.api.controller.PictureController;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.query.ExamStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.lock.LockService;
import cn.com.qmth.stmms.common.enums.LockType;

public class SheetDownloadThread implements Runnable {

    public static final Logger log = LoggerFactory.getLogger(SheetDownloadThread.class);

    private Integer examId;

    private File baseDir;

    private Boolean withTag;

    private PictureController controller;

    private ExamStudentService studentService;

    private LockService lockService;

    public SheetDownloadThread(Integer examId, String dir, Boolean withTag, PictureController controller,
            ExamStudentService studentService, LockService lockService) {
        this.examId = examId;
        this.baseDir = new File(dir);
        this.withTag = withTag;
        this.controller = controller;
        this.studentService = studentService;
        this.lockService = lockService;
    }

    @Override
    public void run() {
        if (!lockService.trylock(LockType.SAVE_SHEET, examId)) {
            return;
        }

        try {
            ExamStudentSearchQuery query = new ExamStudentSearchQuery();
            query.setExamId(examId);
            query.setUpload(true);
            query.setPageSize(100);
            query.setPageNumber(0);
            while (true) {
                query.setPageNumber(query.getPageNumber() + 1);
                query = studentService.findByQuery(query);
                if (query.getCurrentCount() == 0) {
                    break;
                }

                for (ExamStudent student : query.getResult()) {
                    log.info("write for student: " + student.getExamNumber());
                    for (int i = 1; i <= student.getSheetCount(); i++) {
                        download(student, i);
                    }
                }
            }
        } catch (Exception e) {
            log.error("save sheet thread error", e);
        } finally {
            lockService.unlock(LockType.SAVE_SHEET, examId);
        }
    }

    private void download(ExamStudent student, int index) {
        File file = new File(baseDir, examId + File.separator + student.getSubjectCode() + File.separator
                + student.getExamNumber() + "-" + index + ".jpg");
        try {
            file.getParentFile().mkdirs();
            BufferedImage image = ImageBuildUtil.buildTagImage(controller.getSheetImage(student, index),
                    withTag != null && withTag.booleanValue() ? studentService.buildSheetTags(student, index) : null);
            ImageIO.write(image, "jpg", file);
            log.info("write sheet file success: " + file.getAbsolutePath());
        } catch (Exception e) {
            log.error("write sheet file error: " + file.getAbsolutePath(), e);
        }
    }

}
