package boundary;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
// import java.io.*; required for Test code

public class DatabaseCommunicator {
	// default constants
	private static String DB = "group72";
	private static String USERNAME = "group72";
	private static String PASSWORD = "serc567";
	private static String HOST = "software-ece.rutgers.edu";
	private static String PORT = "3306";
	private static Connection connection;
	private static Driver driver;
	private static java.util.Properties info = new java.util.Properties();
	
	public static boolean connect() {
		boolean retval = false;
		if (connection == null) {
			String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DB;
			System.out.println("Connecting to " + url + "...");
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				driver = DriverManager.getDriver(url);
				info.setProperty("user", USERNAME);
				info.setProperty("password", PASSWORD);
				connection = driver.connect(url, info);
				retval = true;
			}
			catch (Exception e) {
				System.err.println("Database Exception: " + e.toString());
				System.err.println("Shutting down...");
				System.exit(1);
			}
		}
		else {
			retval = true;
		}
		return retval;
	}
	
	// takes an SQL query in the form of a String
	// returns a resultset if the query worked. if not, it returns null
	public static ResultSet query(String q) {
		ResultSet rs = null;
		Statement s = null;
		try {
			s = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			if (s.execute(q)) {
				rs = s.getResultSet();
			}
		}
		catch (Exception e) {
			System.out.println("Exception: " + e.toString());
		}
		return rs;
	}

	public static boolean isDatabaseEmpty() {
		boolean retval = true;
		String query = "SELECT symbol FROM stock;";
		ResultSet resultSet = DatabaseCommunicator.query(query);
		try {
			if (resultSet.next()) {
				retval = false;
			}
		}
		catch (Exception e) {
			System.err.println("UC1Controller: " + e.toString());
		}
		return retval;
	}
	
	public static void close() {
		try {
			connection.close();
		}
		catch (Exception e) {
			System.err.println("Could not close MySQL connection: " + e.toString());
		}
	}
	
	public static ResultSet fetchPortfolios() {
		return null;
	}
	
	public static void updatePortfolios() {
	}
		
	/*
	public static void main(String[] args) {
		// BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		ResultSet rs = null;
		System.out.println(DatabaseCommunicator.connect());
		// while (true) {
			try {
				// DatabaseCommunicator.query(bf.readLine());
				String query = "SELECT * FROM stock;";
				rs = DatabaseCommunicator.query(query);
				System.out.println(rs.getFetchSize());
			}
			catch (Exception e) {
				System.err.println("Exception: " + e.toString());
			}
		// }
	}
	*/
	
}