/* File: AddUserPane.java
 * Author: Jason Gookins
 * Description: Allows an admin to add new users to the database.
 */

import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class AddUserPane extends JPanel implements ActionListener
{
	/************************
	 ** Instance Variables **
	 ************************/

	private Belief belief;
	private JTextField usernameTextField;
	private JPasswordField passwordField, confirmField;
	private JRadioButton userRadioButton, adminRadioButton;
	private JButton okayButton, cancelButton;



	/**********************
	 ** Main Constructor **
	 **********************/

	public AddUserPane(Belief belief)
	{
		this.belief = belief;

		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		JLabel addNewUserLabel = new JLabel("Add New User", JLabel.CENTER);
		addNewUserLabel.setFont(new Font("SansSerif", Font.PLAIN, 20));
		addNewUserLabel.setPreferredSize(new Dimension(200, 60));
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 2;
		c.gridheight = 1;
		c.fill = GridBagConstraints.BOTH;
		add(addNewUserLabel, c);

		JPanel inputPanel = new JPanel(new GridBagLayout());
		GridBagConstraints d = new GridBagConstraints();

		JLabel usernameLabel = new JLabel("Username:");
		d.gridx = 0;
		d.gridy = 0;
		d.insets = new Insets(0, 0, 5, 5);
		d.fill = GridBagConstraints.NONE;
		inputPanel.add(usernameLabel, d);

		JLabel passwordLabel = new JLabel("Password:");
		d.gridy = 1;
		d.insets = new Insets(5, 0, 5, 5);
		inputPanel.add(passwordLabel, d);

		JLabel confirmLabel = new JLabel("Confirm Password:");
		d.gridy = 2;
		d.insets = new Insets(5, 0, 0, 5);
		inputPanel.add(confirmLabel, d);

		usernameTextField = new JTextField();
		usernameTextField.setPreferredSize(new Dimension(200, 20));
		usernameTextField.setMinimumSize(new Dimension(200, 20));
		usernameTextField.addActionListener(this);
		d.gridx = 1;
		d.gridy = 0;
		d.insets = new Insets(0, 10, 5, 5);
		d.fill = GridBagConstraints.BOTH;
		inputPanel.add(usernameTextField, d);

		passwordField = new JPasswordField();
		passwordField.setPreferredSize(new Dimension(200, 20));
		passwordField.setMinimumSize(new Dimension(200, 20));
		passwordField.addActionListener(this);
		d.gridy = 1;
		d.insets = new Insets(5, 10, 5, 5);
		inputPanel.add(passwordField, d);

		confirmField = new JPasswordField();
		confirmField.setPreferredSize(new Dimension(200, 20));
		confirmField.setMinimumSize(new Dimension(200, 20));
		confirmField.addActionListener(this);
		d.gridy = 2;
		d.insets = new Insets(5, 10, 0, 5);
		inputPanel.add(confirmField, d);		

		c.gridy = 1;
		add(inputPanel, c);

		ButtonGroup typeGroup = new ButtonGroup();

		userRadioButton = new JRadioButton("Normal User");
		userRadioButton.setSelected(true);
		c.gridy = 2;
		c.gridwidth = 1;
		c.weightx = 0.5;
		c.insets = new Insets(10, 0, 5, 5);
		c.fill = GridBagConstraints.NONE;
		c.anchor = GridBagConstraints.EAST;
		typeGroup.add(userRadioButton);
		add(userRadioButton, c);

		adminRadioButton = new JRadioButton("Administrator");
		c.gridx = 1;
		c.insets = new Insets(10, 5, 5, 0);
		c.anchor = GridBagConstraints.WEST;
		typeGroup.add(adminRadioButton);
		add(adminRadioButton, c);

		okayButton = new JButton("Okay");
		okayButton.setPreferredSize(new Dimension(75, 30));
		okayButton.setMinimumSize(new Dimension(75, 30));
		okayButton.addActionListener(this);
		c.gridx = 0;
		c.gridy = 3;
		c.insets = new Insets(15, 0, 0, 5);
		c.anchor = GridBagConstraints.EAST;
		add(okayButton, c);

		cancelButton = new JButton("Cancel");
		cancelButton.setPreferredSize(new Dimension(75, 30));
		cancelButton.setMinimumSize(new Dimension(75, 30));
		cancelButton.addActionListener(this);
		c.gridx = 1;
		c.insets = new Insets(15, 5, 0, 0);
		c.anchor = GridBagConstraints.WEST;
		add(cancelButton, c);
	}



	/***************
	 ** Accessors **
	 ***************/

	public JTextField getUsernameTextField()
	{
		return this.usernameTextField;
	}



	/*******************
	 ** Action Events **
	 *******************/

	public void actionPerformed(ActionEvent evt)
	{
		if (evt.getSource().equals(usernameTextField))
		{
			passwordField.requestFocus();
		}
		else if (evt.getSource().equals(passwordField))
		{
			confirmField.requestFocus();
		}
		else if (evt.getSource().equals(okayButton) || evt.getSource().equals(confirmField))
		{
			try
			{
				addNewUser();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		else if (evt.getSource().equals(cancelButton))
		{
			returnToAdminChoicePane();
		}
	}



	/**********************
	 ** Instance Methods **
	 **********************/

	private void addNewUser() throws Exception
	{
		String password = new String(passwordField.getPassword());
		String confirmedPassword = new String(confirmField.getPassword());

		if (!password.equals(confirmedPassword))
		{
			AddUserDialog errorDialog = new AddUserDialog("Password Error", "error", new JOptionPane("New password and confirmed password do not match. Please try again.", JOptionPane.ERROR_MESSAGE));
		}
		else
		{
			Class.forName("org.sqlite.JDBC");
			Connection conn = DriverManager.getConnection("jdbc:sqlite:belief.db");
			Statement statement = conn.createStatement();
			String username = usernameTextField.getText();
			ResultSet rs = statement.executeQuery("SELECT name FROM users WHERE name='" + username + "'");

			if (rs.isClosed())
			{
				String userType;

				if (userRadioButton.isSelected())
				{
					userType = "user";
				}
				else
				{
					userType = "admin";
				}

				statement.execute("INSERT INTO users (name, pass, type) VALUES ('" + username + "', '" + confirmedPassword + "', '" + userType + "')");
				conn.close();

				AddUserDialog successDialog = new AddUserDialog("User Added", "success", new JOptionPane("User added successfully.", JOptionPane.INFORMATION_MESSAGE));
			}
			else
			{
				rs.close();
				conn.close();

				AddUserDialog errorDialog = new AddUserDialog("Username Error", "error", new JOptionPane("That username already exists. Please try again.", JOptionPane.ERROR_MESSAGE));
			}
		}
	}

	private void returnToAdminChoicePane()
	{
		CardLayout mainLayout = (CardLayout)belief.getContentPane().getLayout();

		mainLayout.show(belief.getContentPane(), "adminChoicePane");

		clearFields();
	}

	private void clearFields()
	{
		usernameTextField.setText(null);
		passwordField.setText(null);
		confirmField.setText(null);
		usernameTextField.requestFocus();
	}



	/**********************
	 ** Internal Classes **
	 **********************/

	private class AddUserDialog extends InternalModalDialog
	{
		private String type;

		public AddUserDialog(String title, String type, JOptionPane pane)
		{
			super(title, belief, pane);

			this.type = type;
		}

		public void cleanUpAfterClosing()
		{
			if (type.equals("error"))
			{
				clearFields();
				usernameTextField.requestFocus();
			}
			else if (type.equals("success"))
			{
				returnToAdminChoicePane();
			}
		}
	}
}