package backend.service;
import backend.dao.QuestionsDao;
import backend.dao.TestRecordDao;
import backend.dao.UserDao;
import backend.model.Charts;
import backend.model.TestRecord;

import java.util.*;

public class TestRecordService {
    private TestRecordDao testRecordDao = new TestRecordDao();
    private UserDao userDao = new UserDao();
    private QuestionsDao questionsDao = new QuestionsDao();

    private Vector<Vector<String>> commonHandler(List<TestRecord> testRecordList){
        //加工数据 把数据库查到的List转成Vector<Vector<>>
        Vector<Vector<String>> testRecordData = new Vector<>();
        if(testRecordList != null) {
            for (TestRecord testRecordPo : testRecordList) {
                Vector<String> row = new Vector<>();
                row.add(String.valueOf(testRecordPo.getId()));
                row.add(String.valueOf(userDao.findById(testRecordPo.getUserId()).getUsername()));
                row.add(String.valueOf(questionsDao.getById(testRecordPo.getQuestionId()).getName()));
                row.add(String.valueOf(testRecordPo.getScore()));
                row.add(testRecordPo.getAnswer());
                row.add(String.valueOf(testRecordPo.getTime()));
                testRecordData.add(row);
            }
        }
        return testRecordData;
     }
     //获取所有记录 用于管理员
     public Vector<Vector<String>> getAll(){
        //从数据库中获取所有记录
        List<TestRecord> testRecordList = testRecordDao.getAll();
        //把List转成表格所需的格式
        return commonHandler(testRecordList);
        //返回给前端
    }
    //获取指定用户的所有记录 用于用户和管理员
    public Vector<Vector<String>> getByUserId(Integer userId){
        //从数据库中获取所有记录
        List<TestRecord> testRecordList = testRecordDao.getByUserId(userId);
        //把List转成表格所需的格式
        return commonHandler(testRecordList);
        //返回给前端
    }
    //获取指定题目的所有记录 用于管理员和 用户
    public Vector<Vector<String>> getByQuestionId(Integer questionId){
        //从数据库中获取所有记录
        List<TestRecord> testRecordList = testRecordDao.getByQuestionId(questionId);
        //把List转成表格所需的格式
        return commonHandler(testRecordList);
        //返回给前端
    }
    //获取指定用户指定题目的所有记录 用于用户和管理员
    public Vector<Vector<String>> getByUserIdAndQuestionId(Integer userId, Integer questionId){
        //从数据库中获取所有记录
        List<TestRecord> testRecordList = testRecordDao.getByUserIdAndQuestionId(userId, questionId);
        //把List转成表格所需的格式
        return commonHandler(testRecordList);
        //返回给前端
    }
    public boolean insert(TestRecord testRecord){
        //插入新的记录的同时，更新排行榜
        ChartsService chartsService = new ChartsService();
        Charts charts = new Charts();
        charts.setUserid(testRecord.getUserId());
        charts.setScore(testRecord.getScore());
        chartsService.updateCharts(charts);
        return testRecordDao.insert(testRecord);
    }
    public boolean delete(Integer id){
        return testRecordDao.delete(id);
    }


}
