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

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller("examQuestionApiController")
@RequestMapping("/api")
public class ExamQuestionController extends BaseApiController {

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamSubjectService subjectService;

    // @AuthValidate("adminUser")
    @RequestMapping("/objective/{examId}")
    @ResponseBody
    public JSONArray getObjectiveQuestion(HttpServletRequest request, @PathVariable Integer examId) {
        JSONArray result = new JSONArray();
        List<ExamSubject> subjectList = subjectService.list(examId);
        if (subjectList != null) {
            for (ExamSubject subject : subjectList) {
                List<ExamQuestion> list = questionService.findByExamAndSubjectAndObjective(examId, subject.getCode(),
                        true);
                if (list == null || list.isEmpty()) {
                    continue;
                }

                JSONArray array = new JSONArray();
                int index = 0;
                JSONObject current = null;
                for (ExamQuestion question : list) {
                    index++;
                    if (question.getTotalScore() > 0) {
                        if (current == null) {
                            current = new JSONObject();
                            current.accumulate("start", index);
                        }
                    } else {
                        if (current != null) {
                            current.accumulate("end", index - 1);
                            array.add(current);
                            current = null;
                        }
                    }
                }
                if (current != null) {
                    current.accumulate("end", index);
                    array.add(current);
                }

                JSONObject obj = new JSONObject();
                obj.accumulate("subjectCode", subject.getCode());
                obj.accumulate("index", array);
                result.add(obj);
            }
        }
        return result;
    }
}
