package com.zjty.automatedtesting.service.impl;

import com.zjty.automatedtesting.pojo.report.Report;
import com.zjty.automatedtesting.pojo.report.ReportVo;
import com.zjty.automatedtesting.repository.ReportRepository;
import com.zjty.automatedtesting.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    ReportRepository repository;

    @Autowired
    TransHelper transHelper;

    @Override
    public Integer save(Report report) {
        Integer id;
        if (Objects.isNull(report.getId()) || repository.existsById(report.getId())) {
            id = repository.save(report).getId();
        } else {
            throw new RuntimeException("指定的id不存在：" + report.getId());
        }
        return id;
    }

    @Override
    public List<ReportVo> findAll() {
        return repository.findAll().stream().map(transHelper::toReportVo).collect(Collectors.toList());
    }

    @Override
    public List<ReportVo> findByPage(Integer page) {
        PageRequest request = PageRequest.of(page, 10);
        return repository.findAll(request).stream().map(transHelper::toReportVo).collect(Collectors.toList());
    }

    @Override
    public List<ReportVo> findByCaseId(Integer caseId) {
        return repository.findAll().stream()
                .filter(report -> Objects.equals(caseId, report.getCaseId()))
                .map(transHelper::toReportVo)
                .collect(Collectors.toList());
    }

    @Override
    public ReportVo findById(Integer id) {
        Optional<ReportVo> reportVo = repository.findById(id).map(transHelper::toReportVo);
        if (reportVo.isPresent()) {
            return reportVo.get();
        } else {
            throw new RuntimeException("指定id的数据不存在：" + id);
        }
    }

    @Override
    public void delete(Integer id) {
        if (repository.existsById(id)) {
            repository.deleteById(id);
        } else {
            throw new RuntimeException("指定的id不存在：" + id);
        }
    }
}
