package com.zjty.automatedtesting.service.impl;

import com.zjty.automatedtesting.pojo.test.Case;
import com.zjty.automatedtesting.pojo.test.CaseVo;
import com.zjty.automatedtesting.repository.CaseRepository;
import com.zjty.automatedtesting.service.CaseService;
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;

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Service
public class CaseServiceImpl implements CaseService {

    @Autowired
    CaseRepository repository;

    @Autowired
    TransHelper transHelper;

    @Override
    public Integer create(CaseVo caseVo) {
        Integer id;
        if (isNull(caseVo.getId())) {
            Case aCase = transHelper.toTestCase(caseVo);
            id = repository.save(aCase).getId();
        } else {
            throw new RuntimeException("新增不可附带id");
        }
        return id;
    }

    @Override
    public Integer update(CaseVo caseVo) {
        Integer id;
        if (nonNull(caseVo.getId())){
            if (repository.existsById(caseVo.getId())) {
                Case aCase = transHelper.toTestCase(caseVo);
                id = repository.save(aCase).getId();
            } else {
                throw new RuntimeException("指定的id不存在：" + caseVo.getId());
            }
        } else {
            throw new RuntimeException("修改必须附带id");
        }
        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 List<CaseVo> findBySystemId(String systemId) {
        return repository.findAll().stream()
                .filter(aCase -> Objects.equals(aCase.getSystemId(),systemId))
                .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);
        }
    }

}
