package com.zjty.automatedtesting.service;

import com.zjty.automatedtesting.pojo.test.Case;
import com.zjty.automatedtesting.pojo.test.CaseVo;
import com.zjty.automatedtesting.repository.CaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
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 CaseServiceImpl implements CaseService {

    @Autowired
    CaseRepository repository;

    @Autowired
    TransHelper transHelper;

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

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

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

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

}
