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

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.qmth.stmms.api.exception.ApiException;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.query.ExamSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.AnswerCardService;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.ApiUser;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.enums.ExamType;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller("scanExamController")
@RequestMapping("/api/exam")
public class ExamController extends BaseApiController {

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

    @Autowired
    private ExamService examService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private AnswerCardService answerCardService;

    private Exam validateExam(ApiUser au, Integer examId, ExamType... types) {
        Exam exam = examService.findById(examId);
        if (exam == null || !validateSchool(au.getSchoolId(), exam.getSchoolId()) || exam.getStatus() != ExamStatus.START) {
            throw ApiException.EXAM_NOT_ACCESSIBLED;
        }
        if (types != null && types.length > 0 && !Arrays.asList(types).contains(exam.getType())) {
            throw ApiException.QUERY_PARAM_ERROR.replaceMessage("exam type invalid");
        }
        return exam;
    }

    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SCAN_ADMIN })
    @ResponseBody
    public JSONArray examQuery(HttpServletRequest request, ExamSearchQuery query) {
        ApiUser user = RequestUtils.getApiUser(request);
        JSONArray array = new JSONArray();
        query.setSchoolId(user.getSchoolId());
        query.setType(ExamType.SCAN_IMAGE);
        query.setStatus(ExamStatus.START);
        if (query.getPageSize() < 1) {
            query.setPageSize(20);
        }
        query.orderByIdDesc();
        query = examService.findByQuery(query);
        for (Exam exam : query.getResult()) {
            JSONObject obj = new JSONObject();
            obj.accumulate("id", exam.getId());
            obj.accumulate("name", exam.getName());
            obj.accumulate("examTime", exam.getExamTime().getTime());
            if (StringUtils.isNotBlank(exam.getScanConfig())) {
                obj.accumulate("config", exam.getScanConfig());
            }
            array.add(obj);
        }
        return array;
    }

    @RequestMapping(value = "/config/save", method = RequestMethod.POST)
    @RoleRequire({ Role.SCHOOL_ADMIN })
    @ResponseBody
    public JSONObject configSave(HttpServletRequest request, @RequestParam Integer examId, @RequestParam String config) {
        ApiUser au = RequestUtils.getApiUser(request);
        Exam exam = validateExam(au, examId, ExamType.SCAN_IMAGE);
        exam.setScanConfig(StringEscapeUtils.unescapeHtml(config));
        examService.save(exam);
        JSONObject result = new JSONObject();
        result.accumulate("id", examId);
        result.accumulate("name", exam.getName());
        School school = schoolService.findById(au.getSchoolId());
        result.accumulate("schoolName", school.getName());
        result.accumulate("config", StringUtils.trimToEmpty(exam.getScanConfig()));
        result.accumulate("updateTime", System.currentTimeMillis());
        return result;
    }

}
