package cn.stylefeng.team.meta.api.util;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.rule.enums.DbTypeEnum;
import cn.stylefeng.roses.kernel.rule.util.DatabaseTypeUtil;

public class DbNameReplaceUtil {

    public static String replaceDatabaseName(String databaseUrl, String databaseName) {

        if (StrUtil.isBlank(databaseName)) {
            return databaseUrl;
        }

        if (DbTypeEnum.MYSQL.equals(DatabaseTypeUtil.getDbType(databaseUrl))) {

            int firstPosition = databaseUrl.lastIndexOf("/");

            int lastPosition = databaseUrl.lastIndexOf("?");

            StringBuilder sbu = new StringBuilder(databaseUrl);
            sbu.replace(firstPosition + 1, lastPosition, databaseName);
            return sbu.toString();
        }

        else if (DbTypeEnum.PG_SQL.equals(DatabaseTypeUtil.getDbType(databaseUrl))) {

            int firstPosition = databaseUrl.lastIndexOf("/");
            return databaseUrl.substring(0, firstPosition + 1) + databaseName;
        }

        else if (DbTypeEnum.MS_SQL.equals(DatabaseTypeUtil.getDbType(databaseUrl))) {

            int firstPosition = databaseUrl.lastIndexOf("=");
            return databaseUrl.substring(0, firstPosition + 1) + databaseName;
        }

        else if (DbTypeEnum.ORACLE.equals(DatabaseTypeUtil.getDbType(databaseUrl))) {
            return databaseUrl;
        }

        return databaseUrl;
    }

}
