/*
 * Created on Aug 12, 2003
 */
package DatabaseCommunication;

import java.sql.*;
import java.util.*;
import Data.UserData;

/**
 * @author student
 * This class  manages communication of User data with application database.
 * 
 */

public class UserManager {
	DatabaseConnection dbcon = new DatabaseConnection();

	/**
	 * This is the constructor for UserManager.java
	 */
	public UserManager() {
	}
	
	/**
	 * This method is being used to select a user with a particular login Id
	 * @param loginId Id of the user you want to select.
	 * @return user data
	 * @throws Exception UserData
	 */
	public UserData selectUser(String loginId) throws Exception {
		ResultSet rs =
			dbcon.executeSelect(
				"SELECT * FROM user WHERE user.loginId = '" + loginId + "'");

		if (rs.next()) {
			return new UserData(
			//	              stripTrailing(rs.getString("loginId")),
			stripTrailing(rs.getString("fName")),
				stripTrailing(rs.getString("lName")),
				stripTrailing(rs.getString("email")),
				rs.getTimestamp("outFrom"),
				rs.getTimestamp("outTo"));
		}

		return null;

	}
	/**
	 * This method is being used to get the email address of the user 
	 * @param fName Firstname of the user
	 * @param lName Lastname of the user
	 * @return string email address of the user
	 * @throws Exception String
	 */
	public String getEmailAddress(String fName, String lName)
		throws Exception {
		System.out.println("Name whose email we want :" + fName + " " + lName);
		ResultSet rs =
			dbcon.executeSelect(
				"SELECT * FROM user WHERE user.fName = '"
					+ fName
					+ "'"
					+ "AND user.lName ='"
					+ lName
					+ "';");
		String s = "";
		if (rs.next()) {
			s = stripTrailing(rs.getString("email"));
			System.out.println("s :" + s);
		}
		return s;
	}
	/**
	 * This method is being used to get the name of the user using its loginID
	 * @param id login Id of the user
	 * @return string name of the user
	 * @throws Exception String
	 */
	public String getName(String id) throws Exception {
		System.out.println("LoginId whose fName we want :" + id);
		ResultSet rs =
			dbcon.executeSelect(
				"SELECT * FROM user WHERE user.loginId = '" + id + "'");
		String s = "";
		if (rs.next()) {
			s = stripTrailing(rs.getString("fName"));
			s += " ";
			s += stripTrailing(rs.getString("lName"));
			//				+stripTrailing(rs.getString("lName"));
			System.out.println("s :" + s);
		}
		return s;
	}
	/**
	 * This method is being used to select all the registered user 
	 * @return
	 * @throws Exception UserData[]
	 */
	public UserData[] selectAllUsers() throws Exception {
		ResultSet rs = dbcon.executeSelect("SELECT * FROM user");
		UserData[] userArray = new UserData[10];
		for (int i = 0; rs.next(); i++) {
			UserData user = new UserData(
				//					  stripTrailing(rs.getString("loginId")),
	stripTrailing(rs.getString("fName")),
		stripTrailing(rs.getString("lName")),
		stripTrailing(rs.getString("email")),
		rs.getTimestamp("outFrom"),
		rs.getTimestamp("outTo"));
			userArray[i] = user;
		}
		return userArray;
	}

	/**
	 * This method is being used to strip trailing blanks
	 */
	public String stripTrailing(String value)
	// strip trailing blanks...
	{
		if (value == null)
			return "";

		char cs[] = value.toCharArray();

		int end = cs.length;
		while (end > 0 && cs[end - 1] == ' ')
			end--;

		return new String(cs, 0, end);
	}

	/**
	 * This method is being used to insert  User data
	 * @param data User data to be inserted.
	 * @throws Exception void
	 */
	public void insertUserData(Data.UserData data) throws Exception {
		if (ifExists(data) == true) {
			System.out.println("It already exists");
			updateUserData(data);

		} else {
			dbcon.execute(
				"INSERT INTO user (loginId,fName,lName,email,outFrom,outTo,expiryTime) VALUES ("
					+ "'"
					+ data.getLoginId()
					+ "',"
					+ "'"
					+ data.getFName()
					+ "',"
					+ "'"
					+ data.getLName()
					+ "',"
					+ "'"
					+ data.getEmailAddress()
					+ "',"
					+ "'"
					+ data.getOutFrom()
					+ "',"
					+ "'"
					+ data.getOutTo()
					+ "',"
					+ "'"
					+ calculateExpiry(data.getOutTo())
					+ "')");
		}

	}

	/**
	 * This method is being used to update user data
	 * @param data User data to be updated
	 * @throws Exception void
	 */
	public void updateUserData(UserData data) throws Exception {
		dbcon.execute(
			"UPDATE user SET "
				+ " fName = '"
				+ data.getFName()
				+ "',"
				+ " lName = '"
				+ data.getLName()
				+ "',"
				+ " email = '"
				+ data.getEmailAddress()
				+ "',"
				+ " outFrom = '"
				+ data.getOutFrom()
				+ "',"
				+ " outTo = '"
				+ data.getOutTo()
				+ "',"
				+ " expiryTime = '"
				+ calculateExpiry(data.getOutTo())
				+ "'"
				+ " WHERE loginId = '"
				+ data.getLoginId()
				+ "'");

	}

	/**
	 * This method is being used to delete user data
	 * @param data User data to be deleted
	 * @throws Exception void
	 */
	public void deleteUserData(Data.UserData data) throws Exception {
		dbcon.execute(
			"DELETE FROM user WHERE ID = '" + data.getLoginId() + "'");
	}
	/**
	 * This method is being used to check if the user exists.
	 * @param data User data to check
	 * @return boolean true if user exists
	 * @throws Exception boolean
	 */
	private boolean ifExists(Data.UserData data) throws Exception {
		boolean exists = false;
		ResultSet rs = dbcon.executeSelect("SELECT * FROM user");
		while (rs.next()) {
			if (rs.getString("loginId").equals(data.getLoginId())) {
				exists = true;
				return exists;
			}
		}
		return exists;
	}
	/**
	 * This method is being used to calculate expiry of the User data
	 * @param fromTime time the message was created
	 * @return Timestamp expiry of the user data
	 */
	private Timestamp calculateExpiry(Timestamp fromTime) {
		if (fromTime != null) {
			long expiry = addDays(fromTime, 1);
			Timestamp expiryTime = new Timestamp(expiry);
			System.out.println("User Expiry" + expiryTime);
			return expiryTime;
		}
		return null;
	}
	/**
	 * Method: addDays
	 * This method is being used for
	 * @param startDate
	 * @param numberOfDays
	 * @return long
	 */
	public static long addDays(java.util.Date startDate, int numberOfDays) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(startDate);
		cal.add(Calendar.DATE, numberOfDays);
		return cal.getTimeInMillis();

	}
}
