package cn.fateverse.query.handler.adapter;

import cn.fateverse.common.code.model.EngineResult;
import cn.fateverse.query.entity.DataAdapter;
import cn.fateverse.query.handler.reader.EngineExecuteHandlerReader;
import cn.fateverse.query.mapper.DataAdapterMapper;
import org.springframework.util.ObjectUtils;

/**
 * @author Clay
 * @date 2024/4/19 22:44
 */
public abstract class AbstractDataAdapterHandler implements DataAdapterHandler {

    protected final DataAdapterMapper dataAdapterMapper;


    protected final EngineExecuteHandlerReader handlerReader;


    protected AbstractDataAdapterHandler(DataAdapterMapper dataAdapterMapper, EngineExecuteHandlerReader handlerReader) {
        this.dataAdapterMapper = dataAdapterMapper;
        this.handlerReader = handlerReader;
    }

    protected Object execute(Long adapterId, Object data, boolean development) {
        if (ObjectUtils.isEmpty(adapterId)) {
            return data;
        }
        //获取当当前接口对应的数据适配器
        DataAdapter dataAdapter = dataAdapterMapper.selectById(adapterId);
        if (ObjectUtils.isEmpty(dataAdapter)) {
            throw new RuntimeException("dataAdapter is null");
        }
        handlerReader.preconditioning(dataAdapter);
        EngineResult execute = handlerReader.execute(dataAdapter, data, development);
        if (ObjectUtils.isEmpty(execute)) {
            throw new RuntimeException("执行结果错误");
        }
        return execute.getResult();
    }


    protected EngineResult mockExecute(Long adapterId, String code, Object data, boolean development) {
        //获取当当前接口对应的数据适配器
        DataAdapter dataAdapter = dataAdapterMapper.selectById(adapterId);
        if (ObjectUtils.isEmpty(dataAdapter)) {
            throw new RuntimeException("dataAdapter is null");
        }
        dataAdapter.setCode(code);
        handlerReader.preconditioning(dataAdapter);
        EngineResult execute = handlerReader.execute(dataAdapter, data, development);
        if (ObjectUtils.isEmpty(execute)) {
            throw new RuntimeException("执行结果错误");
        }
        dataAdapterMapper.updateCode(dataAdapter);
        return execute;
    }


    @Override
    public boolean remove(Long adapterId) {
        if (ObjectUtils.isEmpty(adapterId)) {
            throw new RuntimeException("adapterId is null");
        }
        DataAdapter dataAdapter = dataAdapterMapper.selectById(adapterId);
        if (ObjectUtils.isEmpty(dataAdapter)) {
            throw new RuntimeException("dataAdapter is null");
        }
        return handlerReader.remove(dataAdapter);
    }

}
