/*****************************************************************
  Used by the LoginValidate servlet.
  The servlet uses this to establish a connection to the database, and determine
  if a set of login information (username/password) is both valid and verified.

  @author Anthony Furst
  @version CISC 474
*/

package com.example.model;

import java.util.*;
import java.lang.*;
import java.sql.*;

public class Validator {
    private Connection myCon;
    private Statement myStmt;

    /** Takes the account information for the database and establishes a connection and a
	SQL statement, both of which will be used later to make queries.
	@param username The username of the database being used.
	@param password The password for the database being used.
	@param url The url of the database being used.
    */
    public void makeConnection(String username, String password, String url) {
	try {
	    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
	}
	catch (Exception e) {
	    e.printStackTrace();
	}
	
	try {
	    myCon = DriverManager.getConnection(url, username, password);
	}
	catch (SQLException e) {
	    e.printStackTrace();
	}

	try {
	    myStmt = myCon.createStatement();
	}
	catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /** Takes the username and password and determines if there exists such an account with
	that combination.
	@param username The username for the account.
	@param password The password for the account.
	@return True if such an account exists, false otherwise.
    */
    public boolean validAccount(String username, String password) {	
	String selectQuery = "SELECT * FROM Account where username='" + username + 
	    "' and password='" + password + "'";
	ResultSet results;
	boolean validLogin = true;

	try {
	    results = myStmt.executeQuery(selectQuery);
	
	    if (!results.next()) {
		validLogin = false;
	    }
	}
	catch (Exception e) {
	    e.printStackTrace();
	}
	finally {
	    return validLogin;
	}
    }

    /** Takes a username and password and determines if there exists such an account with
	that combination which has been verified.
	@param username The username for the account.
	@param password The password for the account.
	@return True if the account is verified, false if it doesn't exist or isn't verified.
    */
    public boolean verifiedAccount(String username, String password) {
	String selectQuery = "SELECT * FROM Account where username='" + username + 
	    "' and password='" + password + "' and Verified='Verified'";
	ResultSet results;
	boolean verifiedLogin = true;

	try {
	    results = myStmt.executeQuery(selectQuery);
	
	    if (!results.next()) {
		verifiedLogin = false;
	    }
	}
	catch (Exception e) {
	    e.printStackTrace();
	}
	finally {
	    return verifiedLogin;
	}
    }
    
    /** Closes the connection and the statement */
    public void closer() {
	try {
	    myCon.close();
	    myStmt.close();
	}
	catch (Exception e) {
	    e.printStackTrace();
	}
    }
}