package tech.easyflow.datacenter.execution.service.impl;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Service;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.datacenter.connector.DatacenterConnector;
import tech.easyflow.datacenter.connector.DatacenterConnectorRegistry;
import tech.easyflow.datacenter.entity.DatacenterTable;
import tech.easyflow.datacenter.execution.model.DatasetRef;
import tech.easyflow.datacenter.meta.entity.DatacenterSource;
import tech.easyflow.datacenter.meta.service.DatacenterDatasetRegistryService;
import tech.easyflow.datacenter.execution.service.DatacenterDatasetWriteService;

import javax.annotation.Resource;
import java.math.BigInteger;

@Service
public class DatacenterDatasetWriteServiceImpl implements DatacenterDatasetWriteService {

    @Resource
    private DatacenterDatasetRegistryService registryService;
    @Resource
    private DatacenterConnectorRegistry connectorRegistry;

    @Override
    public void saveRow(DatasetRef datasetRef, JSONObject data, LoginAccount account) {
        DatacenterTable table = resolveTable(datasetRef);
        DatacenterSource source = registryService.getSourceRequired(table.getSourceId());
        DatacenterConnector connector = connectorRegistry.getConnector(source.getSourceType());
        connector.saveRow(source, table, data, account);
    }

    @Override
    public void deleteRow(DatasetRef datasetRef, BigInteger id, LoginAccount account) {
        DatacenterTable table = resolveTable(datasetRef);
        DatacenterSource source = registryService.getSourceRequired(table.getSourceId());
        DatacenterConnector connector = connectorRegistry.getConnector(source.getSourceType());
        connector.deleteRow(source, table, id, account);
    }

    private DatacenterTable resolveTable(DatasetRef datasetRef) {
        if (datasetRef == null || datasetRef.getTableId() == null) {
            throw new BusinessException("缺少 tableId");
        }
        return registryService.getTableWithFields(datasetRef.getTableId());
    }
}
