package cn.com.qmth.stmms.ms.collect.api;

import cn.com.qmth.stmms.ms.collect.util.RotateTask;
import cn.com.qmth.stmms.ms.commons.config.AliYunOssConfig;
import cn.com.qmth.stmms.ms.commons.config.ImageConfig;
import cn.com.qmth.stmms.ms.commons.config.ImageServerConfig;
import cn.com.qmth.stmms.ms.commons.config.SystemConfig;
import cn.com.qmth.stmms.ms.commons.utils.OssUtil;
import cn.com.qmth.stmms.ms.core.domain.Paper;
import cn.com.qmth.stmms.ms.core.repository.PaperRepo;
import cn.com.qmth.stmms.ms.core.repository.StudentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhengmin on 2017/2/24.
 */
@RestController
@RequestMapping("api/images")
public class ImageApi {

    @Autowired
    private PaperRepo paperRepo;

    @Autowired
    private SystemConfig systemConfig;

    @Autowired
    ImageConfig imageConfig;

    @Autowired
    StudentRepo studentRepo;

    @Resource
    OssUtil ossUtil;

    @Resource
    AliYunOssConfig aliYunOssConfig;

    @Resource
    ImageServerConfig imageServerConfig;

    private ExecutorService executor = Executors.newFixedThreadPool(10);

    private HashSet<String> papers = new HashSet<String>();

    @RequestMapping(value = "{paperId}/rotate", method = RequestMethod.GET)
    public ResponseEntity rotate(@PathVariable Long paperId, @RequestParam int degree) {
        Paper paper = paperRepo.findOne(paperId);
        if (!papers.contains(paper.getExamNumber())) {
            executor.submit(new RotateTask(paper, degree, paperRepo, systemConfig, papers, imageConfig, studentRepo, ossUtil, aliYunOssConfig, imageServerConfig));
            papers.add(paper.getExamNumber());
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    @RequestMapping(value = "process", method = RequestMethod.GET)
    public ResponseEntity process() {
        return new ResponseEntity(papers.size(), HttpStatus.OK);
    }

}
