package core.db;

import core.configuration.ConfigurationMap;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection
{
    private volatile Connection instance;

    public DBConnection(ConfigurationMap configuration) throws SQLException
    {
        this.instance = open(
                configuration.getUrl(),
                configuration.getUsername(),
                configuration.getPassword()
        );
    }

    private DBConnection() {}

    public Connection getInstance()
    {
        return instance;
    }

    private Connection open(String url, String username, String password) throws SQLException
    {
        Connection local = instance;

        if (local == null)
        {
            synchronized (Connection.class)
            {
                local = instance;
                if (local == null)
                {
                    instance = local = DriverManager.getConnection(url, username, password);
                }
            }
        }

        return local;
    }

    public void close() throws SQLException
    {
        instance.close();
        instance = null;
    }
}
