/* this cquery engine has all queries related to the user. */

import java.io.*;
import java.util.*;
import java.sql.*;
//import javax.sql.*;



/* NOTE: you need to take care of the connection as sir said. connection pool etc. one possible soln is to make this class syncronised.*/
public class UserQueryEngine{
    // BidPageGen bpg;
    public Connection con;
    //public ConnectionPoolDataSource cpds;
    //public PooledConnection con;

    // opening the connectin in the constructor
    public UserQueryEngine(){
	try{
	    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	    con=DriverManager.getConnection(Config.connectionInfo, Config.dbaseLogin, Config.dbasePassword);
	}
	catch(SQLException sqle){ // in case of an sql exception
	    System.out.println("Problem occured while connecting to Database..");
	    while(sqle != null){
		System.out.println("SQLState: "+sqle.getSQLState());
		System.out.println("Message: "+sqle.getMessage());
		sqle=sqle.getNextException();
	    }
	}
    }
    
    // returns true if a login, password pair exist. else returns false  //CHECKED
    public boolean isValidUser(String login, String password){
	String queryStatement=null;
	ResultSet rs=null;
	System.out.println("login: "+ login);
	System.out.println("password: "+ password);
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT userLogin FROM Users WHERE userLogin='"+login+"' and password='"+password+"'";
	    System.out.println(queryStatement);
	    rs=stmt.executeQuery(queryStatement);
	    int test=0;
	    while (rs.next()){
		test++;
	    }
	    if(test==0){
		System.out.println("no such user passwd pair exist");
		return false;
	    }
	    else{
		System.out.println("user passwd pair exist");
		return true;
	    }
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
	return false;// in this case some problem with conneciton
    }
    
    
    // returns true if a login exist. else returns false CHECKED
    public boolean isLoginPresent(String login){
	
	System.out.println("login: "+ login);// test print

	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT userLogin FROM Users WHERE userLogin='"+login+"'";
	    System.out.println(queryStatement);
	    rs=stmt.executeQuery(queryStatement);
	    int test=0;
	    while (rs.next()){
		test++;
	    }
	    System.out.println("test="+test);
	    if(test<=0){
		stmt.close();
		System.out.println("rs was null so returning false");
		return false;
	    }
	    else{
		stmt.close();
		System.out.println("rs was not null so returning false");
		return true;
	    }
	}catch(SQLException sqle){
            System.out.println("exception occuresd:"+sqle);
	}
	return false;// in this case some prob with connection
    }

    // returns true if a user is suspended  CHECKED
    public boolean isSuspendedUser(String login){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT isSuspended FROM Users WHERE userLogin='"+login+"' and isSuspended='no'";
	    System.out.println(queryStatement);
	    rs=stmt.executeQuery(queryStatement);
	    int count=0;
	    while (rs.next()){
		count++;
	    }
	    if (count==1){
		System.out.println("done");
		return false;
	    }
	    else{
		return true;
	    }
	    
	}catch(SQLException sqle){
            System.out.println("Exception number 1 " + sqle);
	}
	return false;// in this case some prob with connection
    }

    //adding a user's information in the database CHECKED
    public void addUserInfo(String login, String password, String firstName, String lastName, String email, String gender, String address, String city, String dateOfBirth){
	String updateStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    updateStatement="INSERT INTO Users VALUES ('"+login+"','"+password+"','"+firstName+"','"+lastName+"','"+email+"','"+gender+"','"+address+"','"+city+"','"+dateOfBirth+"', 'no')";
	    System.out.println(updateStatement);
	    stmt.executeUpdate(updateStatement);
	}catch(SQLException sqle){
            System.out.println("Exception number 1" + sqle);
	}
    }

    // Updating a user's info to the database
    public void updateUserInfo(String loginName, String oldPassword, String newPassword, String firstName, String lastName, String email, String gender, String address, String city){
	String updateStatement="";
	ResultSet rs=null;
	if (newPassword.equals("")){
	    updateStatement="UPDATE users SET firstName='"+firstName+"', lastName='"+lastName+"', email='"+email+"', gender='"+gender+"', address='"+address+"', city='"+city+"' WHERE userLogin='"+loginName+"'"; 
	}
	else{
	    updateStatement="UPDATE users SET password='"+newPassword+"',firstName='"+firstName+"', lastName='"+lastName+"', email='"+email+"', gender='"+gender+"', address='"+address+"', city='"+city+"' WHERE userLogin='"+loginName+"'";
	}
	try{    
	    Statement stmt=con.createStatement();
	    stmt.executeUpdate(updateStatement);
	}catch(SQLException sqle){
	    System.out.println("Exception " + sqle);
	}
    }
    
    // will return a ResultSet containing user's info
    public void getUserInfo(PrintWriter out, String login){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT firstName, lastName, email, gender, address, city FROM Users WHERE userLogin='"+login+"'";
	    rs=stmt.executeQuery(queryStatement);
	    // will change user Profile
	    UserPageGenerator.changeProfilePage(out, login, rs);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }

    // will return the details of a successful auctoin for a user
    public void userQueryOne(PrintWriter out, String login){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT SAH.productId, P.productName, SAH.winnerLogin, SAH.winnerPrice, U.email, U.address FROM SuccAuctHistory SAH, Users U, Product P WHERE SAH.winnerLogin=U.userLogin AND P.productId=SAH.productId AND SAH.sellerLogin='"+login+"'";
	    rs=stmt.executeQuery(queryStatement);
	UserPageGenerator.queryOnePage(out, rs, login);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }

    // will return the details of a unsuccessful auction of a user
    public void userQueryTwo(PrintWriter out, String login){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT UAH.productId, P.productName, UAH.startDate, UAH.closingDate  FROM UnsuccAuctHistory UAH, Product P WHERE UAH.productId=P.productId AND UAH.sellerLogin='"+login+"'";
	    rs=stmt.executeQuery(queryStatement);
	    UserPageGenerator.queryTwoPage(out, rs);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }


    // will return details of current auctions of a user
    // it will return two result sets,( actually we divide query three in twofunctions, part1, part2. one containing product with auctions placed on them and other containing products with no auction on them. NOte that both rs's will have different number of attributes. so in UserPageGen class you need to keep it in mind
    
    public void userQueryThree(PrintWriter out, String login){
	String queryStatement=null;
	ResultSet rs1=null, rs2=null;
	try{
	    Statement stmt1=con.createStatement();
	    Statement stmt2=con.createStatement();
	    queryStatement="SELECT CA.productId, P.productName, CA.startDate, CA.closingDate, CA.location, CB.bidderLogin, CB.bidValue FROM CurrentAuction CA, Product P, CurrentBid CB WHERE P.productId=CA.productId AND CA.auctionId=CB.auctionId AND CA.sellerLogin='"+login+"'";
	    rs1=stmt1.executeQuery(queryStatement);
	    queryStatement="SELECT CA.productId, P.productName, CA.startDate, CA.closingDate, CA.location FROM CurrentAuction CA, Product P WHERE P.productId=CA.productId AND CA.sellerLogin='"+login+"' AND CA.auctionId NOT IN (SELECT auctionId FROM currentBid)";
	    rs2=stmt2.executeQuery(queryStatement);
	    UserPageGenerator.queryThreePage(out, rs1, rs2);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }

    // list all auctions for which user has placed bids
    // (data will be taken from curent
    
    public void userQueryFour(PrintWriter out,String login){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT CA.productId, P.productName, CA.location, CA.closingDate, CB.bidValue FROM Product P, CurrentAuction CA, CurrentBid Cb WHERE P.productId=CA.productId AND CB.auctionId=CA.auctionId AND CB.bidderLogin='"+login+"'";
	    rs=stmt.executeQuery(queryStatement);
	    UserPageGenerator.queryFourPage(out, rs);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }

    // will return the details of a auction won by a user
    public void userQueryFive(PrintWriter out, String login){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT SAH.productId, P.productName, SAH.winnerPrice, SAH.sellerLogin, U.email, U.address FROM SuccAuctHistory SAH, Users U, Product P WHERE SAH.sellerLogin=U.userLogin AND P.productId=SAH.productId AND SAH.winnerLogin='"+login+"'";
	    rs=stmt.executeQuery(queryStatement);
	    UserPageGenerator.queryFivePage(out, rs, login);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }

    // will update feedback table when a seller gives feedback on a winner
    public void updateWinnerRatedAs(String productId, String sellerRatedWinnerAs){
	String updateStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    updateStatement="UPDATE Feedback SET sellerRatedWinnerAs='"+sellerRatedWinnerAs+"' WHERE productId='"+productId+"'";
	    stmt.executeUpdate(updateStatement);
	}catch(SQLException sqle){
            System.out.println("Exception while updating winnerRatedAs feedback:" + sqle);
	}
    }

    // will update feedback table when a winner gives feedback on a seller
    public void updateSellerRatedAs(String productId, String winnerRatedSellerAs){
	String updateStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    updateStatement="UPDATE Feedback SET winnerRatedSellerAs='"+winnerRatedSellerAs+"' WHERE productId='"+productId+"'";
	    stmt.executeUpdate(updateStatement);
	}catch(SQLException sqle){
            System.out.println("Exception while updating sellerRatedAs feedback:" + sqle);
	}
    }


    // will insert into feedback table when a seller gives feedback on a winner
    public void insertWinnerRatedAs(String productId, String sellerRatedWinnerAs, String winnerLogin, String sellerLogin){
	String updateStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    updateStatement="INSERT INTO Feedback VALUES ('"+productId+"', '"+winnerLogin+"', '"+sellerLogin+"', null, '"+sellerRatedWinnerAs+"'";
	    stmt.executeUpdate(updateStatement);
	}catch(SQLException sqle){
            System.out.println("Exception while updating insertWinnerRatedAs feedback:" + sqle);
	}
    }


    // will insert into feedback table when a winner gives feedback on a seller
    public void insertSellerRatedAs(String productId, String winnerRatedSellerAs, String winnerLogin, String sellerLogin){
	String updateStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    updateStatement="INSERT INTO Feedback VALUES ('"+productId+"', '"+winnerLogin+"', '"+sellerLogin+"', '"+winnerRatedSellerAs+"', null";
	    stmt.executeUpdate(updateStatement);
	}catch(SQLException sqle){
            System.out.println("Exception while updating insertSellerRatedAs feedback:" + sqle);
	}
    }



    // will return the rating given by winner to seller, if not rated then 'notRated' and if this auction has no entry in feedback table then 'noEntry' 
    public String winnerRatedSellerAs(String productId){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT winnerRatedSellerAs FROM Feedback WHERE productId='"+productId+"'";
	    rs=stmt.executeQuery(queryStatement);
	    int count=0;
	    while (rs.next()){
		count++;
	    }
	    if (count==0)
		return "noEntry";
	    else if ((rs.getString(1)).equals("good") || rs.getString(1).equals("neutral") || rs.getString(1).equals("bad"))
		return rs.getString(1);
	    else
		return "notRated";
	}catch(SQLException sqle){
	    System.out.println("Exception " + sqle);
	    return "";
	}
    }

    // will return the rating given by seller to winner, if not rated then 'notRated' and if this auction has no entry in feedback table then 'noEntry' 
    public String sellerRatedWinnerAs(String productId){
	String queryStatement=null;
	ResultSet rs=null;
	try{
	    Statement stmt=con.createStatement();
	    queryStatement="SELECT sellerRatedWinnerAs FROM Feedback WHERE productId='"+productId+"'";
	    rs=stmt.executeQuery(queryStatement);
	    int count=0;
	    while (rs.next()){
		count++;
	    }
	    if (count==0)
		return "noEntry";
	    else if ((rs.getString(1)).equals("good") || rs.getString(1).equals("neutral") || rs.getString(1).equals("bad"))
		return rs.getString(1);
	    else
		return "notRated";
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	    return "";
	}
    }

    // will return the rating details of a particular user
    public void generalUserRating(String userLogin, PrintWriter out){
	String queryStatement=null;
	ResultSet rs1=null;
	ResultSet rs2=null;
	try{
	    Statement stmt1=con.createStatement();
	    Statement stmt2=con.createStatement();
	    queryStatement="SELECT sellerLogin, sellerRatedWinnerAs FROM Feedback WHERE winnerLogin='"+userLogin+"' and sellerRatedWinnerAs IS NOT NULL";
	    rs1=stmt1.executeQuery(queryStatement);

	    queryStatement="SELECT sellerLogin, winnerRatedSellerAs FROM Feedback WHERE sellerLogin='"+userLogin+"' and winnerRatedSellerAs IS NOT NULL";
	    rs1=stmt1.executeQuery(queryStatement);
	    UserPageGenerator.generalUserRatingTable(out, rs1, rs2);
	}catch(SQLException sqle){
            System.out.println("Exception " + sqle);
	}
    }
}
