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

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

/**
 * @author student
 * This class  manages communication of Message data with application database.
 * 
 */
public class MessageManager {
	DatabaseConnection dbcon = new DatabaseConnection();
	/**
	 * This is the constructor for MessageManager.java
	 */
	//Statement db ;	
	public MessageManager() {
	}

	/**
	 * This method is being used to select all the messages for the user in a particular order.
	 * @param id user the message is for
	 * @return array of selected messages.
	 * @throws Exception MessageData[]
	 */
	public MessageData[] selectAllMessages(String id) throws Exception {
		ResultSet rs =
			dbcon.executeSelect(
				"SELECT * FROM message WHERE toUser ='"
					+ id
					+ "'ORDER BY expiryTime DESC;");
		MessageData[] messageArray = new MessageData[10];
		for (int i = 0; rs.next(); i++) {
			if (rs
				.getTimestamp("expiryTime")
				.after(new Timestamp(System.currentTimeMillis()))) {
				MessageData message =
					new MessageData(
						stripTrailing(rs.getString("fromUser")),
						stripTrailing(rs.getString("toUser")),
						stripTrailing(rs.getString("body")),
						stripTrailing(rs.getString("subject")),
						rs.getTimestamp("time"));
				messageArray[i] = message;
			}
		}
		return messageArray;
	}


//	/**
//	 * This method is being used for
//	 * @param to
//	 * @return
//	 * @throws Exception MessageData
//	 */
//	public MessageData selectMessage(String to) throws Exception {
//		ResultSet rs =
//			dbcon.executeSelect(
//				"SELECT * FROM message WHERE message.to = '" + to + "'");
//
//		if (rs.next()) {
//			return new MessageData(
//				stripTrailing(rs.getString("from")),
//				stripTrailing(rs.getString("to")),
//				stripTrailing(rs.getString("body")),
//				stripTrailing(rs.getString("subject")),
//				rs.getTimestamp("time"));
//		}
//
//		return null;
//
//	}
	/**
	 * This method is being used stripping string 
	 * @param value String which is being stripped
	 * @return String 
	 */
	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 Message data
	 * @param data Message Data to be inserted.
	 * @throws Exception void
	 */
	public void insertMessageData(Data.MessageData data) throws Exception {

		dbcon.execute(
			"INSERT INTO message (fromUser,toUser,body,subject,time,expiryTime) VALUES ("
				+ "'"
				+ data.getFrom()
				+ "',"
				+ "'"
				+ data.getTo()
				+ "',"
				+ "'"
				+ data.getBody()
				+ "',"
				+ "'"
				+ data.getSubject()
				+ "',"
				+ "'"
				+ data.getTime()
				+ "',"
				+ "'"
				+ calculateExpiry(data.getTime())
				+ "')");

	}

	/**
	 * This method is being used to update Message Data
	 * @param data Message Data being updated
	 * @throws Exception void
	 */
	public void updateMessageData(MessageData data) throws Exception {
		dbcon.execute(
			"UPDATE message SET "
				+ " from = '"
				+ data.getFrom()
				+ "',"
				+ " to = '"
				+ data.getTo()
				+ "',"
				+ " body = '"
				+ data.getBody()
				+ "',"
				+ " subject = '"
				+ data.getSubject()
				+ "',"
				+ " time = '"
				+ data.getTime()
				+ "',"
				+ " expiryTime = '"
				+ calculateExpiry(data.getTime())
				+ "'");

	}

	/**
	 * This method is being used to delete Message Data
	 * @param data
	 * @throws Exception void
	 */
	public void deleteMessageData(Data.MessageData data) throws Exception {
		dbcon.execute(
			"DELETE FROM message WHERE time = '" + data.getTime() + "'");
	}
	/**
	 * This method is being used to calculate expiry of the message data
	 * @param fromTime time the message was created
	 * @return Timestamp expiry of the message data
	 */
	private Timestamp calculateExpiry(Timestamp fromTime) {
		if (fromTime != null) {
			long expiry = addDays(fromTime, 1);
			Timestamp expiryTime = new Timestamp(expiry);
			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();

	}
}
