package com.qiaoba.module.tenant.handler;

import com.qiaoba.common.base.enums.DataBaseEnum;
import com.qiaoba.common.base.exceptions.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理器工厂-根据不同类型的数据库-选择不同的处理器
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/8 15:34
 */
@Component
@RequiredArgsConstructor
public class DataHandlerFactory {

    private static Map<String, DataHandler> handlerMap = new ConcurrentHashMap<>();

    private final MysqlDataHandler mysqlDataHandler;
    private final OracleDataHandler oracleDataHandler;
    private final PostgreSqlHandler postgreSqlHandler;
    private final SqlServerHandler sqlServerHandler;

    @PostConstruct
    public void register() {
        handlerMap.put(DataBaseEnum.MY_SQL.getType(), mysqlDataHandler);
        handlerMap.put(DataBaseEnum.ORACLE.getType(), oracleDataHandler);
        handlerMap.put(DataBaseEnum.POSTGRE_SQL.getType(), postgreSqlHandler);
        handlerMap.put(DataBaseEnum.SQL_SERVER.getType(), sqlServerHandler);
    }

    public static DataHandler getHandler(String name) {
        DataHandler dataHandler = handlerMap.get(name);
        if (Objects.isNull(dataHandler)) {
            throw new ServiceException("数据库处理器工厂异常, 类型:[" + name + "]找不到相对应的解析器");
        }
        return dataHandler;
    }
}
