/* © SRSoftware 2025 */
package de.srsoftware.umbrella.core;

import static java.lang.System.Logger.Level.INFO;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import org.sqlite.SQLiteDataSource;

public class ConnectionProvider {
	private static final System.Logger LOG = System.getLogger(ConnectionProvider.class.getSimpleName());
	private static final HashMap<File, Connection> connections = new HashMap<>();

	private ConnectionProvider(){}

	public static Connection connect(Object o) {
		if (o instanceof String filename) o = new File(filename);
		if (o instanceof File dbFile) try {
			var conn = connections.get(dbFile);
			if (conn == null) {
				connections.put(dbFile, conn = open(dbFile));
				LOG.log(INFO,"Using {0}",dbFile);
			}
			return conn;
		} catch (SQLException sqle) {
			throw new RuntimeException(sqle);
		}
		return null;
	}

	private static Connection open(File dbFile) throws SQLException {
		SQLiteDataSource dataSource = new SQLiteDataSource();
		dataSource.setUrl("jdbc:sqlite:%s".formatted(dbFile));
		return dataSource.getConnection();
	}
}
