package db;

import java.sql.Statement;
import java.util.Optional;
import java.util.logging.Logger;

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

public class Database {
	
	private static final Logger LOGGER = Logger.getLogger(Database.class.getName());
	private static Connection db;
	
	static {
		ini();
		unset();
		setup();
	}
	
	public static void ini() {
		try{
		    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
		} catch(ClassNotFoundException e){
		    LOGGER.warning("Unable to find Derby driver");
		    throw new IllegalStateException("Unable to connect to the database", e);
		}
		try {
			db = DriverManager.getConnection("jdbc:derby:microfolie;create=true");
		} catch (SQLException e) {
			LOGGER.warning(e.getMessage());
			throw new IllegalStateException("Unable to connect to the database", e);
		}
	}
	
	public static void close() {
		if(db != null) {
			try {
				db.close();
				db = null;
			} catch (SQLException e) {
				LOGGER.warning(e.getMessage());
				throw new IllegalStateException("Unable to close database connection", e);
			}	
		}
	}
	
	public static void setup() {
		if(isSet()) {
			return;
		}
		LOGGER.info("Creating table");
		ManageTable.create.forEach((table, sql) -> {
			LOGGER.info("Creating table " + table);
			execute(sql);
		});
	}
	
	public static void unset() {
		if(!isSet()) {
			return;
		}
		LOGGER.info("Dropping table");
		ManageTable.drop.forEach((table, sql) -> {
			LOGGER.info("Dropping table " + table);
			execute(sql);
		});
	}
	
	public static Optional<ResultSet> query(String sql) {
		try(Statement st = db.createStatement()) {
			ResultSet result = st.executeQuery(sql);
			return Optional.of(result);
		} catch (SQLException e) {
			LOGGER.warning(e.getMessage());
			return Optional.empty();
		}
	}
	
	public static boolean execute(String sql) {
		try(Statement st = db.createStatement()) {
			int result = st.executeUpdate(sql);
			return result == 1;
		} catch (SQLException e) {
			LOGGER.warning(e.getMessage());
			return false;
		}
	}
	
	public static boolean isSet() {
		return query("Select * From Espace").isPresent();
	}
	
	public static Connection getDb() {
		return db;
	}

}
