package dmi_demo;

import java.io.*;
import java.sql.*;

public class ProblemSolver {
	private Connection dbconn;
	public static final int SELL = 1;
	public static final int BUY = 2;

	public ProblemSolver() throws SQLException, ClassNotFoundException, IOException 
	{
		dbconn = DmiDB.connect();
		dbconn.setAutoCommit(false);
	}
	
	public void solve()
	{
		int numAttempts = 10;
		Solution bestsol = null;
		
		for (int i = 0; i < numAttempts; i ++) {
			Solution sol = new Solution();
			sol.populateRandom(dbconn);
			System.out.println("Found random solution "+i);
			int count = 0;
			boolean done = false;
			while (!done) {
				float value = sol.getValue();
				System.out.println ("Current value of solution "+i+" is "+value+", attempting improvement in iteration "+(++count)+"...");
				done = !sol.improve(dbconn);
			}
			System.out.println ("Solution complete.  Value is "+sol.getValue()); 
			if (bestsol == null || sol.getValue() > bestsol.getValue()) {
				System.out.println("This is the best result so far.");
				bestsol = sol;
			} else {
				System.out.println("This is worse than a previous solution; discarding.");
			}
		}
		System.out.println();
		if (bestsol != null) {
			System.out.println("Problem solved! Displaying best solution:");
			bestsol.record(dbconn);
			displayTransactions();
			System.out.println("Value of solution: $"+bestsol.getValue());
		} else {
			System.out.println("Failed to find any solutions, somehow.");
		}
	}
	
	public void displayTransactions()
	{
		try {
			String sql = "SELECT * FROM DMI_Transaction, DMI_Company AS seller, " +
					"DMI_Company AS buyer, DMI_Part " +
					"WHERE DMI_Transaction.Seller_Id=seller.Id " +
					"AND DMI_Transaction.Buyer_Id=buyer.Id " +
					"AND DMI_Transaction.Part_Id=DMI_Part.Id";
			PreparedStatement ps = dbconn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				String seller = rs.getString("seller.Name");
				String buyer = rs.getString("buyer.Name");
				String part = rs.getString("Description");
				Float price = rs.getFloat("Price");
				System.out.println (seller +" sold "+part+" to "+buyer+" for $"+price);
			}
			rs.close();
			ps.close();
		} catch (SQLException e) {
			System.out.println("SQL Exception while trying to record solution to database: "+e.getMessage());
		}
	}
}

