package cn.stylefeng.team.meta.db.sdk.config.builder;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.team.meta.api.pojo.db.DatabaseTableDTO;
import cn.stylefeng.team.meta.api.pojo.db.TableDescription;
import cn.stylefeng.team.meta.db.sdk.IDatabaseQuery;
import cn.stylefeng.team.meta.db.sdk.config.DataSourceConfig;
import jakarta.validation.constraints.NotNull;

import java.util.ArrayList;
import java.util.List;

public class ConfigBuilder {

    private final List<DatabaseTableDTO> tableList = new ArrayList<>();

    private final List<String> tableNameList = new ArrayList<>();

    private final DataSourceConfig dataSourceConfig;

    public ConfigBuilder(@NotNull DataSourceConfig dataSourceConfig) {
        this.dataSourceConfig = dataSourceConfig;
    }

    @NotNull
    public List<DatabaseTableDTO> getTableList() {
        if (tableList.isEmpty()) {
            List<DatabaseTableDTO> genDatabaseTableDTOList = new IDatabaseQuery.DefaultDatabaseQuery(this).queryTables();
            if (!genDatabaseTableDTOList.isEmpty()) {
                this.tableList.addAll(genDatabaseTableDTOList);
            }
        }
        return tableList;
    }

    @NotNull
    public List<String> getTableNameList() {
        if (tableNameList.isEmpty()) {
            List<String> tableNames = new IDatabaseQuery.DefaultDatabaseQuery(this).queryTableNames();
            if (ObjectUtil.isNotEmpty(tableNames)) {
                this.tableNameList.addAll(tableNames);
            }
        }
        return tableNameList;
    }

    @NotNull
    public List<TableDescription> getTableDescriptions() {
        List<TableDescription> tableNames = new IDatabaseQuery.DefaultDatabaseQuery(this).queryTableDescriptions();
        if (ObjectUtil.isNotEmpty(tableNames)) {
            return tableNames;
        } else {
            return new ArrayList<>();
        }
    }

    @NotNull
    public List<DatabaseTableDTO> getTableList(List<String> tableNameList) {
        if (tableList.isEmpty()) {
            List<DatabaseTableDTO> genDatabaseTableDTOList = new IDatabaseQuery.DefaultDatabaseQuery(this).queryTablesByTableNameList(tableNameList);
            if (!genDatabaseTableDTOList.isEmpty()) {
                this.tableList.addAll(genDatabaseTableDTOList);
            }
        }
        return tableList;
    }

    @NotNull
    public DataSourceConfig getDataSourceConfig() {
        return dataSourceConfig;
    }

}
