package cn.com.qmth.examcloud.core.questions.service.bean.context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;

import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetail;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailStruct;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailUnit;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailUnitStruct;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.service.bean.condition.Condition;

public class DetailContext extends Context {

    private PaperContext paperContext;

    private PaperDetailStruct detailStruct;

    private List<UnitContext> units;

    public DetailContext(PaperDetailStruct detailStruct, PaperContext paperContext, List<Condition> conditions) {
        super(conditions);
        this.detailStruct = detailStruct;
        this.units = new LinkedList<UnitContext>();
        this.paperContext = paperContext;
        for (PaperDetailUnitStruct unit : detailStruct.getPaperDetailUnitStructs()) {
            units.add(new UnitContext(unit, this, conditions));
        }
    }

    public boolean check(Question question) {
        return super.check(question) && paperContext.check(question);
    }

    public void select(Question question) {
        super.select(question);
        paperContext.select(question);
    }

    public boolean finish() {
        return selectQues.size() == units.size();
    }

    public Map<PaperDetail, List<PaperDetailUnit>> build(PaperDetailStruct detailStruct) {
        Map<PaperDetail, List<PaperDetailUnit>> detailMap = new HashMap<>();
        PaperDetail pd = new PaperDetail();
        List<PaperDetailUnit> unitList = new ArrayList<>();
        pd.setId(new ObjectId().toString());
        for (int i = 0; i < units.size(); i++) {
            UnitContext uc = units.get(i);
            PaperDetailUnit pdu = uc.build(uc.getUnitStruct());
            pdu.setPaperDetail(pd);
            unitList.add(pdu);
        }
        pd.setUnitCount(detailStruct.getDetailCount());
        pd.setName(detailStruct.getName());
        pd.setTitle(detailStruct.getRemark());
        pd.setNumber(detailStruct.getNumber());
        pd.setScore(detailStruct.getTotalScore());
        detailMap.put(pd, unitList);
        return detailMap;
    }

    public PaperContext getPaperContext() {
        return paperContext;
    }

    public PaperDetailStruct getDetailStruct() {
        return detailStruct;
    }

    public List<UnitContext> getUnits() {
        return units;
    }

}
