package com.purui.prims.dscheduler.service;

import com.purui.prims.common.config.DolphinSchedulerConfig;
import com.purui.prims.dscheduler.model.Datasource;
import com.purui.prims.headless.api.pojo.enums.DolphineSchedulerType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DolphinScheduler数据源服务
 * @author charlie
 * @date 2024/7/26
 */
@Service
public class DatasourceService extends AbstractSchedulerService {
    public DatasourceService(DolphinSchedulerConfig config,
                             RestTemplate restTemplate) {
        super(config, restTemplate);
        // 默认doris
        if (StringUtils.isEmpty(config.getSourceType())) {
            config.setSourceType("DORIS");
        }
        if (StringUtils.isEmpty(config.getTargetType())) {
            config.setSourceType("DORIS");
        }
    }

    // 获取数据源id
    public int getSourceId() {
        if (StringUtils.isEmpty(config.getSourceName())) {
            return 0;
        }
        List<Datasource> datasourceList = getDatasourceList(config.getSourceType());
        if (datasourceList != null) {
            Datasource datasource = datasourceList.stream().filter(d -> d.getName().equals(config.getSourceName())).findFirst().orElse(null);
            if (datasource != null) {
                return datasource.getId();
            }
        }
        return 0;
    }

    public String getSourceType() {
        return config.getSourceType();
    }

    // 获取目标数据源id
    public int getTargetId() {
        if (StringUtils.isEmpty(config.getTargetName())) {
            return 0;
        }
        List<Datasource> datasourceList = getDatasourceList(config.getTargetType());
        if (datasourceList != null) {
            Datasource datasource = datasourceList.stream().filter(d -> d.getName().equals(config.getTargetName())).findFirst().orElse(null);
            if (datasource != null) {
                return datasource.getId();
            }
        }
        return 0;
    }

    public String getTargetType() {
        return this.config.getTargetType();
    }

    private List<Datasource> getDatasourceList(String type) {
        Map<String, Object> data = new HashMap<>(1);
        data.put("type", type);
        return runSchedulerListX(0L, 0L, DolphineSchedulerType.DATASOURCE_LIST,
            data,
            Datasource.class);
    }
}
