/*
 * Created on Aug 1, 2003
 */
package Interface;

import Data.*;
import DatabaseCommunication.*;
import Validators.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;

/**
 * @author student
 * This class is being used for implement the message functionality.
 * 
 */
public class TabMessage
	extends JPanel
	implements ActionListener, ListSelectionListener {

	final static JLabel timeLabel = new JLabel("Time :");
	final static JLabel subjectLabel = new JLabel("Subject :");
	final static JLabel postSubjectLabel = new JLabel("Subject :");
	final static JLabel messageLabel = new JLabel("Message :");
	final static JLabel fromLabel = new JLabel("From :");
	final static JLabel label = new JLabel("Time     Message");
	final static JLabel postLabel = new JLabel("Post    Messages");
	static JList listM;
	static DefaultListModel listModel;

	static JTextField from = new JTextField();
	static JTextArea messageArea = new JTextArea(5, 5);
	static JTextArea postArea = new JTextArea();
	static JTextArea subjectArea = new JTextArea(2, 5);
	static JTextArea postSubject = new JTextArea(2, 5);
	static JTextField timeBoxM = new JTextField();
	static JCheckBox sms = new JCheckBox("SMS");

	static JButton readButton = new JButton("READ");
	static JButton postButton = new JButton("POST");
	static JLabel message = new JLabel();
	static JComboBox comboBoxN;
	static DefaultComboBoxModel comboBoxModel;

	static MessageData[] messageArray;
	static UserData[] userArray;
	static MessageData messagedata = new MessageData();
	private static UserData user;

	/**
	 * This is the constructor for TabMessage.java
	 */
	public TabMessage() {
		super();
	}
	/**
	 * This is the constructor for TabMessage.java for a particular user
	 */
	public TabMessage(UserData user) {
		this.user = user;
	}
	/**
	 * This method is being used to create Message Tab
	 * @return JPanel
	 */
	public JPanel createTabMessage() {

		listModel = new DefaultListModel();
		JPanel aPanel = new JPanel();
		aPanel.setLayout(new BoxLayout(aPanel, BoxLayout.X_AXIS));
		JPanel titledLeftBorders = new JPanel();

		TitledBorder readTitled =
			BorderFactory.createTitledBorder("Read Messages");
		JPanel read = new JPanel();
		read.setBorder(readTitled);
		read.setLayout(new BoxLayout(read, BoxLayout.Y_AXIS));

		listModel = new DefaultListModel();
		fillMessages();

		listM = new JList(listModel);
		listM.setFont(new Font("Times New Roman", Font.BOLD, 12));
		listM.setModel(listModel);
		listM.addListSelectionListener(this);
		listM.setVisibleRowCount(5);
		listM.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		listM.setLayoutOrientation(JList.VERTICAL);
		listM.setVisibleRowCount(-1);

		JScrollPane listScroller = new JScrollPane(listM);
		listScroller.setPreferredSize(new Dimension(250, 50));
		read.add(listScroller);
		JPanel listPane = new JPanel();
		listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));

		label.setLabelFor(listM);
		listPane.add(label);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.add(listScroller);
		listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		read.add(listPane);

		read.add(readButton);
		readButton.setActionCommand("read");
		readButton.addActionListener(this);

		read.add(timeLabel);
		timeLabel.setLabelFor(timeBoxM);
		timeBoxM.setEditable(false);
		read.add(timeBoxM);

		read.add(subjectLabel);
		subjectLabel.setLabelFor(subjectArea);
		read.add(subjectArea);
		subjectArea.setEditable(false);
		subjectArea.setLineWrap(true);
		JScrollPane scrollSubject = new JScrollPane(subjectArea);
		scrollSubject.setPreferredSize(new Dimension(10, 25));
		scrollSubject.setHorizontalScrollBarPolicy(
			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		read.add(scrollSubject);

		read.add(messageLabel);
		messageLabel.setLabelFor(messageArea);
		read.add(messageArea);
		messageArea.setEditable(false);
		subjectArea.setLineWrap(true);
		JScrollPane scrollMessage = new JScrollPane(messageArea);
		scrollMessage.setPreferredSize(new Dimension(10, 50));
		scrollMessage.setHorizontalScrollBarPolicy(
			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		read.add(scrollMessage);

		read.add(fromLabel);
		fromLabel.setLabelFor(from);
		read.add(from);
		from.setEditable(false);

		titledLeftBorders.add(read);
		aPanel.add(titledLeftBorders, BorderLayout.WEST);
		JPanel rightTitledBorders = new JPanel();

		TitledBorder rightTitled = BorderFactory.createTitledBorder("Post");
		JPanel post = new JPanel();
		post.setBorder(rightTitled);
		post.setLayout(new BoxLayout(post, BoxLayout.Y_AXIS));

		post.add(postSubjectLabel);
		post.add(postSubject);
		postSubject.setEditable(true);
		postSubject.setLineWrap(true);
		JScrollPane scrollPostSubject = new JScrollPane(postSubject);
		scrollPostSubject.setPreferredSize(new Dimension(10, 25));
		scrollPostSubject.setHorizontalScrollBarPolicy(
			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		post.add(scrollPostSubject);

		postArea.setEditable(true);
		postArea.setLineWrap(true);
		JScrollPane scrollPane = new JScrollPane(postArea);
		scrollPane.setPreferredSize(new Dimension(50, 100));
		scrollPane.setHorizontalScrollBarPolicy(
			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		post.add(scrollPane);

		post.add(sms);
		//Container for names
		comboBoxModel = new DefaultComboBoxModel();
		populateComboBox();
		comboBoxN = new JComboBox(comboBoxModel);
		comboBoxN.setModel(comboBoxModel);
		comboBoxN.addActionListener(this);
		post.add(comboBoxN);

		//post Button
		postButton.setActionCommand("post");
		postButton.addActionListener(this);
		post.add(postButton);
		rightTitledBorders.add(post);
		message.setPreferredSize(new Dimension(200, 50));
		post.add(message);
		aPanel.add(rightTitledBorders, BorderLayout.EAST);

		return aPanel;
	}

	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		if (command == "read") {
			display(listM.getSelectedIndex());
		} else if (command == "post") {
			UserManager uManager = new UserManager();

			String name = "";
			try {
				name = uManager.getName(user.getLoginId());
			} catch (Exception exp) {
			}
			//create message object				
			//set message properties		
			messagedata.setFrom(name);
			messagedata.setTo(comboBoxN.getSelectedItem().toString());
			messagedata.setBody(postArea.getText());
			messagedata.setSubject(postSubject.getText());
			//get the current time	
			long currentTime = System.currentTimeMillis();
			messagedata.setTime(new Timestamp(currentTime));
			updateDatabase();
		} else
			message.setText("");
	}

	/**
	 * This method is being used to display all messages in the list
	 *  void
	 */
	public static void fillMessages() {
		MessageManager mManager = new MessageManager();
		messageArray = new MessageData[10];
		try {
			UserManager uManager = new UserManager();
			String name = uManager.getName(user.getLoginId());
			//UserData user = new UserData();
			messageArray = mManager.selectAllMessages(name);
			//long from = addDays(new Date(System.currentTimeMillis()),1);

			for (int i = 0; i < messageArray.length; i++) {
				if (messageArray[i] != null) {
					long expiry = addDays(messageArray[i].getTime(), 1);
					Timestamp expiryTime = new Timestamp(expiry);
					if (expiryTime
						.after(new Timestamp(System.currentTimeMillis())))
						listModel.addElement(
							messageArray[i].getTime().getHours()
								+ ":"
								+ messageArray[i].getTime().getMinutes()
								+ "   "
								+ messageArray[i].getSubject());
					else
						listModel.removeElement(
							messageArray[i].getTime().getHours()
								+ ":"
								+ messageArray[i].getTime().getMinutes()
								+ "   "
								+ messageArray[i].getSubject());
					listM.setModel(listModel);
				}
			}
		} catch (Exception exp) {}
	}
	/**
	 * This method is being used to populate the combobox with names
	 */
	public static void populateComboBox() {
		UserManager uManager = new UserManager();
		userArray = new UserData[10];
		try {
			userArray = uManager.selectAllUsers();
			for (int i = 0; i < userArray.length; i++) {
				if (userArray[i] != null) {
					comboBoxModel.addElement(
						userArray[i].getFName()
							+ " "
							+ userArray[i].getLName());
					comboBoxN.setModel(comboBoxModel);
				}
			}
		} catch (Exception exp) {
			//					message.setText("Error while updating message list "+exp.toString());
		}
	}
	/**
	 * This method is being used to send sms
	 *  void
	 */
	public static void sendSMS() {
		String fName = "";
		String lName = "";
		try {

			UserManager uManager = new UserManager();
			StringTokenizer st =
				new StringTokenizer(comboBoxN.getSelectedItem().toString());
			while (st.hasMoreTokens()) {
				fName = st.nextToken();
				lName = st.nextToken();
			}

			String[] sendEmailTo = { uManager.getEmailAddress(fName, lName)};
			System.out.println("Sending email to " + sendEmailTo);

			Mail.postMail(
				sendEmailTo,
				postSubject.getText(),
				postArea.getText());
		} catch (Exception exp) {
			System.out.println("Exception :" + exp.toString());
		}
	}

	/**
	 * This method is being used to refresh the list or messages and the combobox of names
	 */
	public void refresh() {
		listModel = new DefaultListModel();
		fillMessages();
		comboBoxModel = new DefaultComboBoxModel();
		populateComboBox();
	}
	/* (non-Javadoc)
	 * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
	 */
	public void valueChanged(ListSelectionEvent e) {
	}
	private void display(int i) {
		String time = messageArray[i].getTime().toString();
		String subject = messageArray[i].getSubject();
		timeBoxM.setText(time);
		subjectArea.setText(subject);
		messageArea.setText(messageArray[i].getBody());
		from.setText(messageArray[i].getFrom());
	}
	/**
	 * This method is being used to update the message in the database
	 *  void
	 */
	public static void updateDatabase() {

		//Checking for valid time field before updating the database
		MessageValidator mValidator = new MessageValidator();
		boolean validMessage = mValidator.validate(messagedata);

		if (!validMessage) {
			message.setText(mValidator.getMessage());
			return;
		}
		if (sms.isSelected()) {
			sendSMS();
		}
		//update the database
		MessageManager mManager = new MessageManager();
		try {
			mManager.insertMessageData(messagedata);
			message.setText("Message has been posted");
		} catch (Exception exp) {
			//message.setText("Error while posting message "+exp.toString());
			message.setText(
				"Message could not be posted .Please try again later.");
		}

	}
	/**
	 * This method is being used for to add days
	 * @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();

	}
}
