package ink.wgink.database.manager;

import ink.wgink.database.enums.ConnectionTypeEnum;
import ink.wgink.database.manager.entity.ActiveConnection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: ConnectionManager
 * @Description: 连接管理器
 * @Author: wanggeng
 * @Date: 2021/10/27 4:31 下午
 * @Version: 1.0
 */
public class ActiveConnectionManager {
    private static ActiveConnectionManager connectionManager = ConnectionManagerBuilder.CONNECTION_MANAGER;
    private Map<String, ActiveConnection> mysqlConnectionMap = new ConcurrentHashMap<>();

    private ActiveConnectionManager() {
    }

    public static ActiveConnectionManager getInstance() {
        return connectionManager;
    }

    public void add(ConnectionTypeEnum connectionTypeEnum, String id, Connection connection) {
        if (ConnectionTypeEnum.MYSQL.equals(connectionTypeEnum)) {
            mysqlConnectionMap.put(id, new ActiveConnection(id, connection));
        }
    }

    public ActiveConnection getActiveConnection(ConnectionTypeEnum connectionTypeEnum, String id) {
        if (ConnectionTypeEnum.MYSQL.equals(connectionTypeEnum)) {
            return mysqlConnectionMap.get(id);
        }
        return null;
    }

    public Connection getConnection(ConnectionTypeEnum connectionTypeEnum, String id) {
        ActiveConnection activeConnection = getActiveConnection(connectionTypeEnum, id);
        if (activeConnection == null) {
            return null;
        }
        activeConnection.setLastUpdateTime(System.currentTimeMillis());
        return activeConnection.getConnection();
    }

    public void closeConnection(ConnectionTypeEnum connectionTypeEnum, String id) throws SQLException {
        ActiveConnection activeConnection = getActiveConnection(connectionTypeEnum, id);
        if (activeConnection == null) {
            return;
        }
        Connection connection = activeConnection.getConnection();
        if (connection.isClosed()) {
            return;
        }
        connection.close();
        mysqlConnectionMap.remove(id);
    }


    public static class ConnectionManagerBuilder {
        public static ActiveConnectionManager CONNECTION_MANAGER = new ActiveConnectionManager();
    }

}
