package org.a6v.mecha.db.derby;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.apache.derby.jdbc.EmbeddedDriver;

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

public class EmbeddedDerby implements Closeable {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(EmbeddedDerby.class);
    private final String databaseName;
    private final String databaseURL;

    public EmbeddedDerby(String databaseName) throws SQLException {
        DriverManager.registerDriver(new EmbeddedDriver());
        this.databaseName = databaseName;
        databaseURL = "jdbc:derby:" + databaseName + ";create=true";
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(databaseURL);
    }

    public void close() {
        logger.info("Attempting to shut down derby database. [name: {}]", databaseName);
        try {
            DriverManager.getConnection("jdbc:derby:;shutdown=true");
        } catch (SQLException e) {
            // Do nothing
        }
    }
}
