/*
 * Created on Aug 22, 2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package DatabaseCommunication;
import DataClasses.*;
import java.sql.*;
import java.util.*;
import java.io.*;

/**
 * @author student
 *
 * This class is being used for managing stocks in the application
 * database.
 * 
 */
public class StockManager {
	private Connection con;
	
	/**
	 * This is the constructor for StockManager.java
	 */
	public StockManager() {
		try {
			Properties p = new Properties();
			System.out.println("DIR: " + System.getProperty("user.dir"));
			p.load(new FileInputStream("stocktrading.txt"));
			String url = p.getProperty("MYSQLURL");
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection(url, "root", "password");
			System.out.println(
				"Now connected to the Stock Trading database from Stock manager.");
		} catch (Exception e) {
			System.out.println(
				"Stock Manager constructor exception : " + e.toString());
			;

		}

	}
	/**
	 * Method: readAllStocks
	 * This method is being used for reading all the stocks resident
	 * in the application database.
	 * @return Stock_Data[] The set of all retrieved stocks.
	 */
	public Stock_Data[] readAllStocks() {
		try {

			String query = "SELECT * FROM stock;";
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(query);

			int counter = 0;
			while (rs.next()) {
				counter++;
			}

			Stock_Data[] stocks = new Stock_Data[counter];

			rs = stmt.executeQuery(query);

			for (int i = 0; i < counter; i++) {
				rs.next();
				Stock_Data temp =
					new Stock_Data(
						rs.getString(1),
						rs.getString(2),
						rs.getString(3),
						rs.getString(4),
						rs.getString(5),
						rs.getString(6),
						rs.getString(7));
				stocks[i] = temp;
			}

			return stocks;
		} catch (Exception e) {
			System.out.println("Database Exception : " + e.toString());
			return null;
		}
	}
}
