package com.mooctest.controller;

import com.mooctest.data.BugDTO;
import com.mooctest.data.TaskDTO;
import com.mooctest.model.MasterReport;
import com.mooctest.service.BugReportService;
import com.mooctest.service.MasterReportService;
import com.mooctest.service.TaskService;
import com.mooctest.util.ReportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

@Controller
public class TaskController {

    @Autowired
    TaskService taskService;

    @Autowired
    BugReportService bugReportService;

    @Autowired
    MasterReportService masterReportService;
    @GetMapping("/home")
    public String home(Model model) {

        List<TaskDTO> tasks = taskService.getAllTasks();
        model.addAttribute("tasks", tasks);
        return "task_list";
    }

    @GetMapping("/task_detail")
    public String taskDetail(@RequestParam("examId") long examId,
                             @RequestParam("caseId") long caseId,
                             Model model) {

        boolean aggregated = masterReportService.isAggregated(examId, caseId);
        List<BugDTO> allReports = bugReportService.getAllBugs(examId, caseId);
        if (aggregated) {

            List<String> bugIds = allReports.stream().map(BugDTO::getId).collect(Collectors.toList());
            List<MasterReport> mrs = masterReportService.getByBugIds(bugIds);
            Map<String, MasterReport> mrMap = mrs.stream().collect(toMap(MasterReport::getBugId, Function.identity()));
            allReports.forEach(bug -> {
                MasterReport mr = mrMap.get(bug.getId());
                bug.setStatus(mr.getStatus());
                bug.setReviewerId(mr.getReviewerId());
                bug.setMasterId(mr.getMasterId());
            });
        }

        TaskDTO task = taskService.getByExamIdAndCaseId(examId, caseId);
        model.addAttribute("aggregated", aggregated);
        model.addAttribute("allReports", allReports);
        model.addAttribute("severity2String", ReportUtil.severity2String);
        model.addAttribute("recurrent2String", ReportUtil.recurrent2String);
        model.addAttribute("task", task);
        model.addAttribute("reviewMap", ReportUtil.reviewerMap);
        model.addAttribute("examId", examId);
        model.addAttribute("caseId", caseId);
        return "task_detail";
    }
}
