package me.blackphreak;

import me.blackphreak.Debug.Debug;
import me.blackphreak.Debug.DebugLevel;

import java.sql.*;

public class Database {
	// ref.: http://www.runoob.com/sqlite/sqlite-java.html
	Connection conn;
	
	private static Database instance;
	
	public static Database getInstance() {
		return instance != null ? instance : (instance = new Database());
	}
	
	private Database() {
		connect();
	}
	
	private boolean connect() {
		try {
			// connect to sqlite
			try {
				Class.forName("org.sqlite.JDBC");
				conn = DriverManager.getConnection("jdbc:sqlite:students.db");
			}
			catch ( Exception e ) {
				Debug.err("Failed to connect to database. Error: " + e.getMessage());
				conn.close();
				System.exit(1);
			}
			
			Debug.log(DebugLevel.INFO.getLevel() | DebugLevel.DEBUG.getLevel(),
					1,
					"Connect to database successful."
			);
		}
		catch (Exception ex) {
			Debug.err("Fatal error! Failed to connect to the database.");
			ex.printStackTrace();
			Debug.err("Exiting... [Code: 1]");
			System.exit(1);
		}
		return true;
	}
	
	public ResultSet query(String sql) {
		ResultSet rs = null;
		try {
			Statement stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			Debug.err("Query failed.");
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public void close() {
		try {
			conn.close();
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
