package com.qiaoba.common.base.enums;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.exceptions.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://{}:{}/{}?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowMultiQueries=true",
            "com.mysql.cj.jdbc.Driver"),

    /**
     * Oracle
     */
    ORACLE("Oracle",
            "jdbc:oracle:thin:@//localhost:1521/{}",
            "oracle.jdbc.OracleDriver"),

    /**
     * PostgreSQL
     */
    POSTGRE_SQL("PostgreSQL",
            "jdbc:postgresql://localhost:5432/{}?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true",
            "org.postgresql.Driver"),

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

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

    public static DataBaseEnum find(String databaseProductName) {
        if (StrUtil.isBlank(databaseProductName)) {
            return null;
        }
        for (DataBaseEnum type : values()) {
            if (type.getType().equals(databaseProductName)) {
                return type;
            }
        }
        return null;
    }

    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 database) {
        for (DataBaseEnum dataBaseEnum : values()) {
            if (dataBaseEnum.getType().equals(type)) {
                return StrUtil.format(dataBaseEnum.url, ip, port, database);
            }
        }
        throw new ServiceException(StrUtil.format("未找到数据库Url, Type: {}", type));
    }
}
