package backend.service;

import backend.dao.QuestionsDao;
import backend.model.Questions;
import backend.model.enums.GlobalData;

import java.util.HashSet;
import java.util.List;
import java.util.Vector;

public class QuestionsService {
    private QuestionsDao questionsDao = new QuestionsDao();
    private static HashSet<Questions> questionsSet = new HashSet<>();
    private Vector<Vector<String>> commonHandler(List<Questions> questionsList){
        //加工数据 把数据库查到的List转成Vector<Vector<>>
        Vector<Vector<String>> questionsData = new Vector<>();
        if(questionsList != null) {
            for (Questions questionsPo : questionsList) {
                Vector<String> row = new Vector<>();
                row.add(String.valueOf(questionsPo.getId()));
                row.add(questionsPo.getName());
                row.add(questionsPo.getDescription());
                row.add(questionsPo.getAnswer());
                row.add(GlobalData.FREQUENCY_MAP.get(questionsPo.getFrequency()));
                questionsData.add(row);
            }
        }
        return questionsData;
    }
    public Vector<Vector<String>> getAll(){
        //从数据库中获取所有题目
        List<Questions> questionsList = questionsDao.getAll();
        //把List转成表格所需的格式
        return commonHandler(questionsList);
        //返回给前端
    }

    public Vector<Vector<String>> getByCondition(Integer frequency,String key){
        //从数据库中获取所有题目
        List<Questions> wordPoList = questionsDao.getByCondition(frequency,key);
        //把List转成表格所需的格式
        return commonHandler(wordPoList);
    }
    public boolean insert(Questions question){
        return questionsDao.insert(question);
    }
    public void delete(Integer id){
        questionsDao.delete(id);
    }
    public boolean update(Questions question){
        return questionsDao.update(question);
    }

    public Questions getRandomQuestion() {
        //使用红黑树实现的集合防止重复刷同一个题
        if(questionsSet.isEmpty()) {
            Questions question = questionsDao.getRandomQuestion();
            questionsSet.add(question);
            return question;
        }
        while(true) {
            Questions question = questionsDao.getRandomQuestion();
            if(!questionsSet.contains(question)) {
                questionsSet.add(question);
                return question;
            }
        }
    }
}
