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

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

import org.bson.types.ObjectId;

import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
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.PaperStruct;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.service.bean.condition.Condition;

public class PaperContext extends Context {

    private PaperStruct paperStruct;

    private List<DetailContext> details;

    public PaperContext(PaperStruct paperStruct, List<Condition> conditions) {
        super(conditions);
        this.paperStruct = paperStruct;
        this.details = new LinkedList<DetailContext>();
        for (PaperDetailStruct pd : paperStruct.getPaperDetailStructs()) {
            details.add(new DetailContext(pd, this, conditions));
        }
    }

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

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

    public List<Object> build(PaperStruct paperStruct) {
        List<Object> list = new ArrayList<>();
        Paper paper = new Paper();
        paper.setId(new ObjectId().toString());
        paper.setPaperDetailCount(details.size());
        paper.setTotalScore(paperStruct.getTotalScore());
        paper.setPaperType(PaperType.GENERATE);
        List<PaperDetailUnit> units = new ArrayList<>();
        List<PaperDetail> detailList = new ArrayList<>();
        for (DetailContext dc : details) {
            Map<PaperDetail, List<PaperDetailUnit>> tempMap = dc.build(dc.getDetailStruct());
            PaperDetail pd = tempMap.keySet().iterator().next();
            units.addAll(tempMap.get(pd));
            detailList.add(pd);
            pd.setPaperDetailUnits(tempMap.get(pd));
        }
//        PaperUtil.sortDetails(detailList);
        list.add(paper);
        list.add(detailList);
        list.add(units);
        return list;
    }

    public boolean finish() {
        boolean finish = false;
        for (DetailContext dc : details) {
            finish = dc.finish() && finish;
        }
        return finish;
    }

    public PaperStruct getPaperStruct() {
        return paperStruct;
    }

    public List<DetailContext> getDetails() {
        return details;
    }

}
