package org.matrix.database.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.matrix.database.entity.TestCase;
import org.matrix.database.entity.TestCaseBTO;
import org.matrix.database.entity.TestData;
import org.matrix.database.mapper.TestCaseMapper;
import org.matrix.database.mapper.TestDataMapper;
import org.matrix.database.service.ITestDataService;
import org.matrix.exception.GlobalException;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * ITestDataServiceImpl.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2022/2/22 at 3:06 PM
 * Suffering is the most powerful teacher of life.
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Service
public class TestDataServiceImpl extends ServiceImpl<TestDataMapper, TestData> implements ITestDataService {

    private final TestDataMapper dataMapper;

    private final TestCaseMapper caseMapper;

    public TestDataServiceImpl(TestDataMapper dataMapper, TestCaseMapper caseMapper) {
        this.dataMapper = dataMapper;
        this.caseMapper = caseMapper;
    }

    /**
     * 根据testData主键id 转换出TestCaseBTO对象,多用于动态参数绑定中
     *
     * @param testDataId testData的主键id
     * @return {@link TestCaseBTO} 特指某个单条数据的测试用例，多用于动态参数绑定中
     */
    @Override
    public TestCaseBTO toCaseBTO(Long testDataId) {
        TestData testData = Optional.ofNullable(dataMapper.selectById(testDataId))
                .orElseThrow(() -> new GlobalException(String.format("没有找到testDataId = %d 的testData对象 ", testDataId)));

        TestCase testCase = Optional.ofNullable(caseMapper.selectById(testData.getTestCaseId()))
                .orElseThrow(() -> new GlobalException(String.format("在testDataId = %d的绑定对象中 没有找到testCaseId = %d 的testCase对象 ",
                        testDataId, testData.getTestCaseId())));


        return new TestCaseBTO(testCase, testData);
    }

    /**
     * {{@link #toCaseBTO(Long)}} 的重载方法
     *
     * @param testData 一条testData数据对象
     */
    @Override
    public TestCaseBTO toCaseBTO(TestData testData) {
        TestCase testCase = Optional.ofNullable(caseMapper.selectById(testData.getTestCaseId()))
                .orElseThrow(() -> new GlobalException(String.format("在testDataId = %d的绑定对象中 没有找到testCaseId = %d 的testCase对象 ",
                        testData.getId(), testData.getTestCaseId())));

        return new TestCaseBTO(testCase, testData);

    }
}
