package com.qiaoba.common.base.enums;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.exception.ServiceException;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 数据库类型
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/22 16:41
 */
@Getter
@AllArgsConstructor
public enum DataBaseEnum {

    // ip/port/database

    /**
     * MySQL
     */
    MY_SQL("MySQL",
            "jdbc:mysql://{}:{}/{}?databaseTerm=SCHEMA&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowMultiQueries=true",
            "com.mysql.cj.jdbc.Driver",
            "SELECT 1"),

    /**
     * PostgreSQL
     */
    POSTGRE_SQL("PostgreSQL",
            "jdbc:postgresql://{}:{}/{}?currentSchema={}&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowMultiQueries=true",
            "org.postgresql.Driver",
            "SELECT 1"),

    /**
     * SQL Server
     */
    SQL_SERVER("Microsoft SQL Server",
            "jdbc:sqlserver://localhost:1433;DatabaseName={};SelectMethod=cursor;encrypt=false;rewriteBatchedStatements=true",
            "com.microsoft.sqlserver.jdbc.SQLServerDriver",
            "SELECT 1");

    private final String type;
    private final String url;
    private final String driver;
    private final String checkSql;


    public static String getDriver(String type) {
        for (DataBaseEnum dataBaseEnum : values()) {
            if (dataBaseEnum.getType().equals(type)) {
                return dataBaseEnum.driver;
            }
        }
        throw new ServiceException(StrUtil.format("未找到数据库驱动, Type: {}", type));
    }

    public static String getUrl(String type, String ip, String port, String dbName, String schema) {
        for (DataBaseEnum dataBaseEnum : values()) {
            if (dataBaseEnum.getType().equals(type)) {
                return StrUtil.format(dataBaseEnum.url, ip, port, dbName, schema);
            }
        }
        throw new ServiceException(StrUtil.format("未找到数据库Url, Type: {}", type));
    }

    public static String getCheckSql(String type) {
        for (DataBaseEnum dataBaseEnum : values()) {
            if (dataBaseEnum.getType().equals(type)) {
                return dataBaseEnum.checkSql;
            }
        }
        throw new ServiceException(StrUtil.format("未找到数据库checkSql, Type: {}", type));
    }

    public static String getIp(String url, String driver) {
        for (DataBaseEnum dataBaseEnum : values()) {
            if (dataBaseEnum.getDriver().equals(driver)) {
                url = url.replaceFirst(url.substring(0, dataBaseEnum.url.indexOf(StrUtil.EMPTY_JSON)), "");
                return url.split(StrUtil.COLON)[0];
            }
        }
        throw new ServiceException(StrUtil.format("未找到数据库IP, Driver: {}", driver));
    }

}
