/*
 * This file defines an object which retrieves data
 * from a database table cars(name,image)
 * where name is a string and image is a blob.
 *
 * The getCarList method retrieves a list of the
 * names of all cars in the database.
 *
 * The getImage method retrieves a picture of a
 * car, given the car's name, as an
 * input stream.
 */

// You need to import the java.sql package to use JDBC
import java.sql.*;
import java.io.*;
import java.util.*;

class DatabaseAccess {

  Connection conn;

  DatabaseAccess()
  {
    try {
      // Connect to the database
      String url = "jdbc:mysql://sql.cs.oberlin.edu/cardb?";
      String parms = "user=alice&password=tiger&useSSL=false";
      conn = DriverManager.getConnection(url+parms);
    }
    catch (SQLException e){
      System.out.println(e);
      System.exit(1);
    }
  }

  public List<String> getCarList() {
    List<String> result = new ArrayList<String>();
    try {
      Statement stmt = conn.createStatement();
      ResultSet rset = stmt.executeQuery("select name from cars order by name");
      while(rset.next())
	result.add(rset.getString(1));
    }
    catch(SQLException e){
      System.out.println(e);
      result = new ArrayList<String>();
    }
    return result;
  }

  public InputStream getImageStream(String name) {
    InputStream stream = null;
    try {
      String stmtString = "select image from cars where name = ?";
      PreparedStatement stmt = conn.prepareStatement(stmtString);
      stmt.setString(1,name);

      ResultSet rset = stmt.executeQuery();

      Blob blob = null;
      if(rset.next()){
	blob = rset.getBlob("image");
	if(blob!=null)
	  stream = blob.getBinaryStream();
      }
    }
    catch (SQLException e){
      e.printStackTrace();
    }
    return stream==null?null:stream;
  }
}
