/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sand.client.gui;

import java.util.List;
import java.util.UUID;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import sand.client.CredentialTuple;
import sand.client.SandClientManager;

/**
 *
 * @author spencer
 */
public class SandActionsGUI extends javax.swing.JFrame {
	private SandClientManager manager;
	private SandClientGUI parentWindow;

	/**
	 * Creates new form SandActionsGUI
	 */
	public SandActionsGUI(SandClientManager man, SandClientGUI gui, boolean offlineMode) {
		manager = man;
		parentWindow = gui;
		initComponents();
		if(offlineMode) {
			goToOfflineMode();
		}
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		addPanel = new javax.swing.JPanel();
		addButton = new javax.swing.JButton();
		txtserviceAdd = new javax.swing.JTextField();
		txtusernameAdd = new javax.swing.JTextField();
		txtpasswordAdd = new javax.swing.JTextField();
		lblserviceAdd = new javax.swing.JLabel();
		lblusernameAdd = new javax.swing.JLabel();
		lblpasswordAdd = new javax.swing.JLabel();
		lbldescriptionAdd = new javax.swing.JLabel();
		txtdescriptionAdd = new javax.swing.JTextField();
		lookupPanel = new javax.swing.JPanel();
		txtserviceLookup = new javax.swing.JTextField();
		lblserviceLookup = new javax.swing.JLabel();
		lookupButton = new javax.swing.JButton();
		lookupAllbutton = new javax.swing.JButton();
		editPanel = new javax.swing.JPanel();
		lblserviceEdit = new javax.swing.JLabel();
		txtserviceEdit = new javax.swing.JTextField();
		editButton = new javax.swing.JButton();
		removePanel = new javax.swing.JPanel();
		lblserviceRemove = new javax.swing.JLabel();
		txtserviceRemove = new javax.swing.JTextField();
		lblusernameRemove = new javax.swing.JLabel();
		txtusernameRemove = new javax.swing.JTextField();
		removeButton = new javax.swing.JButton();
		removeAllButton = new javax.swing.JButton();
		menuBar = new javax.swing.JMenuBar();
		fileMenu = new javax.swing.JMenu();
		fileMenuViewLogs = new javax.swing.JMenuItem();
		fileMenuLogoff = new javax.swing.JMenuItem();
		userMenu = new javax.swing.JMenu();
		userMenuEditInfo = new javax.swing.JMenuItem();
		userMenuRemoveAccount = new javax.swing.JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent evt) {
				formWindowClosing(evt);
			}
		});

		addPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Add Credential")));

		addButton.setText("Add");
		addButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				addButtonActionPerformed(evt);
			}
		});

		lblserviceAdd.setText("Service");

		lblusernameAdd.setText("Username");

		lblpasswordAdd.setText("Password");

		lbldescriptionAdd.setText("Description");

		javax.swing.GroupLayout addPanelLayout = new javax.swing.GroupLayout(addPanel);
		addPanel.setLayout(addPanelLayout);
		addPanelLayout.setHorizontalGroup(
			addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(addPanelLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
					.addGroup(addPanelLayout.createSequentialGroup()
						.addComponent(lbldescriptionAdd)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtdescriptionAdd))
					.addGroup(addPanelLayout.createSequentialGroup()
						.addComponent(lblserviceAdd)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtserviceAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(lblusernameAdd)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtusernameAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
					.addGroup(addPanelLayout.createSequentialGroup()
						.addComponent(lblpasswordAdd)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtpasswordAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
					.addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
				.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		addPanelLayout.setVerticalGroup(
			addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(addPanelLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(txtserviceAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(txtusernameAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(txtpasswordAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(lblserviceAdd)
					.addComponent(lblusernameAdd)
					.addComponent(lblpasswordAdd))
				.addGap(18, 18, 18)
				.addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(lbldescriptionAdd)
					.addComponent(txtdescriptionAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(addButton))
				.addContainerGap(20, Short.MAX_VALUE))
		);

		lookupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Lookup Credential"));

		lblserviceLookup.setText("Service");

		lookupButton.setText("Lookup");
		lookupButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				lookupButtonActionPerformed(evt);
			}
		});

		lookupAllbutton.setText("Lookup all Credentials");
		lookupAllbutton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				lookupAllbuttonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout lookupPanelLayout = new javax.swing.GroupLayout(lookupPanel);
		lookupPanel.setLayout(lookupPanelLayout);
		lookupPanelLayout.setHorizontalGroup(
			lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(lookupPanelLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addGroup(lookupPanelLayout.createSequentialGroup()
						.addComponent(lblserviceLookup)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtserviceLookup))
					.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, lookupPanelLayout.createSequentialGroup()
						.addGap(0, 0, Short.MAX_VALUE)
						.addGroup(lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
							.addComponent(lookupButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
							.addComponent(lookupAllbutton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))))
				.addContainerGap())
		);
		lookupPanelLayout.setVerticalGroup(
			lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(lookupPanelLayout.createSequentialGroup()
				.addGap(23, 23, 23)
				.addGroup(lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(txtserviceLookup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(lblserviceLookup))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(lookupButton)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
				.addComponent(lookupAllbutton)
				.addContainerGap())
		);

		editPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Edit Credential"));

		lblserviceEdit.setText("Service");

		editButton.setText("Edit");
		editButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				editButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout editPanelLayout = new javax.swing.GroupLayout(editPanel);
		editPanel.setLayout(editPanelLayout);
		editPanelLayout.setHorizontalGroup(
			editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(editPanelLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
					.addComponent(editButton, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addGroup(editPanelLayout.createSequentialGroup()
						.addComponent(lblserviceEdit)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtserviceEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)))
				.addContainerGap(20, Short.MAX_VALUE))
		);
		editPanelLayout.setVerticalGroup(
			editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(editPanelLayout.createSequentialGroup()
				.addGap(24, 24, 24)
				.addGroup(editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(lblserviceEdit)
					.addComponent(txtserviceEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(editButton)
				.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);

		removePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Remove Credential"));

		lblserviceRemove.setText("Service");

		lblusernameRemove.setText("Username");

		removeButton.setText("Remove");
		removeButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				removeButtonActionPerformed(evt);
			}
		});

		removeAllButton.setText("Remove All Credentials");
		removeAllButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				removeAllButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout removePanelLayout = new javax.swing.GroupLayout(removePanel);
		removePanel.setLayout(removePanelLayout);
		removePanelLayout.setHorizontalGroup(
			removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
			.addGroup(removePanelLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addGroup(removePanelLayout.createSequentialGroup()
						.addComponent(lblserviceRemove)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtserviceRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(lblusernameRemove)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(txtusernameRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
					.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, removePanelLayout.createSequentialGroup()
						.addGap(0, 0, Short.MAX_VALUE)
						.addGroup(removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
							.addComponent(removeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
							.addComponent(removeAllButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))))
				.addContainerGap())
		);
		removePanelLayout.setVerticalGroup(
			removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(removePanelLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(lblserviceRemove)
					.addComponent(txtserviceRemove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(lblusernameRemove)
					.addComponent(txtusernameRemove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(removeButton)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
				.addComponent(removeAllButton)
				.addContainerGap())
		);

		fileMenu.setText("File");

		fileMenuViewLogs.setText("View Logs");
		fileMenuViewLogs.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				fileMenuViewLogsActionPerformed(evt);
			}
		});
		fileMenu.add(fileMenuViewLogs);

		fileMenuLogoff.setText("Logout");
		fileMenuLogoff.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				fileMenuLogoffActionPerformed(evt);
			}
		});
		fileMenu.add(fileMenuLogoff);

		menuBar.add(fileMenu);

		userMenu.setText("User");

		userMenuEditInfo.setText("Edit User Info");
		userMenuEditInfo.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				userMenuEditInfoActionPerformed(evt);
			}
		});
		userMenu.add(userMenuEditInfo);

		userMenuRemoveAccount.setText("Delete User Account");
		userMenuRemoveAccount.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				userMenuRemoveAccountActionPerformed(evt);
			}
		});
		userMenu.add(userMenuRemoveAccount);

		menuBar.add(userMenu);

		setJMenuBar(menuBar);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addContainerGap()
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addComponent(removePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(addPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(layout.createSequentialGroup()
						.addComponent(lookupPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(editPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
				.addContainerGap())
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(addPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
					.addComponent(lookupPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(editPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(removePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addContainerGap())
		);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
		// TODO add your handling code here:
		String service = txtserviceAdd.getText();
		String user = txtusernameAdd.getText();
		String pass = txtpasswordAdd.getText();
		String desc = txtdescriptionAdd.getText();
		if(service.equals("") || user.equals("") || pass.equals("")) {
				// These are required
				System.out.println("Service, Username, AND Password are required");
				JOptionPane.showMessageDialog(this, "Service, Username, AND Password are required", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
				return;
		} else {
				System.out.println("Adding credential...");
				UUID uuid = manager.addCredential(service, user, pass, desc);

				if (uuid == null) {
						System.out.println("Add credential FAILED!");
						JOptionPane.showMessageDialog(this, "Add credential FAILED.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
				} else {
						System.out.println("Credential added.");//was added with ID " + uuid.toString());
						clearFields(1);
						JOptionPane.showMessageDialog(this, "Credential added.", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE);
				}
		}
	}//GEN-LAST:event_addButtonActionPerformed

	private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
		int toEdit = -1;
		String service = txtserviceEdit.getText();
		if(service.equals("")) {
				System.out.println("Service is required");
				JOptionPane.showMessageDialog(this, "Service is required.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
				return;
		} else {
			List<CredentialTuple> creds = manager.lookupMatching(service, null);
			if (creds == null || creds.isEmpty()) {
						System.out.println("Credentials of hostname " + service + " not found");
						JOptionPane.showMessageDialog(this, "Credentials of hostname " + service + " not found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
						return;
			} else if (creds.size() == 1) { // Only one to edit
				toEdit = 0;
			} else { // multiple edit
				Object[] possibilities = new Object[creds.size()];
				int i;
				for (i = 0; i < creds.size(); i++) {
					possibilities[i] = i+1 + ") " + creds.get(i).username + " " + creds.get(i).password;
				}
				String response = (String)JOptionPane.showInputDialog(
									this,
									"Select the credential you would like to edit:",
									"Credential Select",
									JOptionPane.PLAIN_MESSAGE,
									null,
									possibilities,
									"");

				if (response != null && response.length() > 0) {
					response = response.substring(0,1);
                    try {
    					toEdit = (Integer.parseInt(response)) - 1;
                    } catch (NumberFormatException e) {
                        toEdit = 0; // don't know what else to do
                    }
				} else { // cancel was hit or nothing was selected
					return;
				}

			}
			// new edit window load with data save a new one and remove the old
			EditCredGUI frame = new EditCredGUI(manager, creds.get(toEdit));
			frame.setTitle("S.A.N.D.");
			frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			frame.pack();
			frame.setVisible(true);
			clearFields(3);
		}
	}//GEN-LAST:event_editButtonActionPerformed

	private void lookupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lookupButtonActionPerformed
		// TODO add your handling code here:
		String service = txtserviceLookup.getText();
		if(service.equals("")) {
				System.out.println("Service is required");
				JOptionPane.showMessageDialog(this, "Service is required.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
				return;
		} else {
				List<CredentialTuple> creds = manager.lookupMatching(service, null);

				if (creds == null || creds.size() == 0) {
						System.out.println("Credentials of hostname " + service + " not found");
						JOptionPane.showMessageDialog(this, "Credentials of hostname " + service + " not found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
						return;
				}
				clearFields(2);
				LookupTableGUI frame = new LookupTableGUI(creds);
				frame.setTitle("S.A.N.D.");
				frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
				frame.pack();
				frame.setVisible(true);
		}
	}//GEN-LAST:event_lookupButtonActionPerformed

	private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed

                int toRemove = -1;
		String service = txtserviceRemove.getText();
		String user = txtusernameRemove.getText();
		if(service.equals("") || user.equals("")) {
				//System.out.println("Service AND Username is required");
				JOptionPane.showMessageDialog(this, "Service AND Username is required", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
				return;
		} else {
			List<CredentialTuple> creds = manager.lookupMatching(service, user);
			if (creds == null || creds.isEmpty()) {
						//System.out.println("Credentials of hostname " + service + " not found");
						JOptionPane.showMessageDialog(this, "Credentials of hostname " + service + " not found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
						return;
			} else if (creds.size() == 1) { // Only one to edit
				toRemove = 0;
			} else { // multiple available to remove
				Object[] possibilities = new Object[creds.size()];
				int i;
				for (i = 0; i < creds.size(); i++) {
					possibilities[i] = i+1 + ") " + creds.get(i).username + " " + creds.get(i).password + " " + creds.get(i).description;
				}
				String response = (String)JOptionPane.showInputDialog(
									this,
									"Select the credential you would like to delete:",
									"Credential Select",
									JOptionPane.PLAIN_MESSAGE,
									null,
									possibilities,
									"");

				if (response != null && response.length() > 0) {
					response = response.substring(0,1);
                                    try {
                                                        toRemove = (Integer.parseInt(response)) - 1;
                                    } catch (NumberFormatException e) {
                                        toRemove = 0; // don't know what else to do
                                    }
				} else { // cancel was hit or nothing was selected
					return;
				}
			}
                        CredentialTuple cred = creds.get(toRemove);
                        boolean success = manager.removeCredential(cred.getUUID());
                        if(success) {
                            clearFields(4);
                            JOptionPane.showMessageDialog(this, "Removal Succeeded", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(this, "Remove credential failed.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
                        }

		}
	}//GEN-LAST:event_removeButtonActionPerformed

	private void fileMenuViewLogsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuViewLogsActionPerformed
		int numLogs = 20;
                try {
                    String s = (String)JOptionPane.showInputDialog(this,"How many log entries back would you like to view?", "Logs",
                                    JOptionPane.PLAIN_MESSAGE, null, null,"");

                    numLogs = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, "Must enter a valid number. Default to 20 log entries.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
                    numLogs = 20;
                }

                List<String> logs = manager.getUserLogs(numLogs);
                LogsGUI gui = new LogsGUI(logs);
		gui.setTitle("S.A.N.D.");
		gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		gui.pack();
		gui.setVisible(true);
	}//GEN-LAST:event_fileMenuViewLogsActionPerformed

	private void fileMenuLogoffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuLogoffActionPerformed
		logout();
	}//GEN-LAST:event_fileMenuLogoffActionPerformed

	private void userMenuEditInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userMenuEditInfoActionPerformed
		EditUserInfoGUI frame = new EditUserInfoGUI(manager);
		frame.setTitle("S.A.N.D.");
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}//GEN-LAST:event_userMenuEditInfoActionPerformed

	private void lookupAllbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lookupAllbuttonActionPerformed
		List<CredentialTuple> creds = manager.lookupAll();

		if (creds == null || creds.isEmpty()) {
				JOptionPane.showMessageDialog(this, "No Credentials Found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
				return;
		} else {
				LookupTableGUI frame = new LookupTableGUI(creds);
				frame.setTitle("S.A.N.D.");
				frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
				frame.pack();
				frame.setVisible(true);
		}
	}//GEN-LAST:event_lookupAllbuttonActionPerformed

	private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
		boolean shouldLogout = logout();
		if(!shouldLogout) {
			return;
		}
	}//GEN-LAST:event_formWindowClosing

	private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed
		 int selectedOption = JOptionPane.showConfirmDialog(null,
								  "Are you sure you want to remove ALL Credentials?",
								  "Remove all?",
								  JOptionPane.YES_NO_OPTION);
		if (selectedOption == JOptionPane.YES_OPTION) {
			boolean success = manager.removeCredential(null,null,true);
			if(success) {
				JOptionPane.showMessageDialog(this, "Credentials all removed", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(this, "Not all credentials could be removed", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
			}
		} else {
			// Do Nothing
		}
	}//GEN-LAST:event_removeAllButtonActionPerformed

	private void userMenuRemoveAccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userMenuRemoveAccountActionPerformed
		int selectedOption = JOptionPane.showConfirmDialog(null,
								  "Are you sure you want to delete your account? This will erase all credentials and remove your account.",
								  "Delete Account?",
								  JOptionPane.YES_NO_OPTION);
		if (selectedOption == JOptionPane.YES_OPTION) {
			boolean success = manager.deleteAccount();
			if (success) {
				JOptionPane.showMessageDialog(this, "Account deleted", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(this, "Account deletion failed", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE);
			}
		}
	}//GEN-LAST:event_userMenuRemoveAccountActionPerformed

	private boolean logout() {
		int selectedOption = JOptionPane.showConfirmDialog(null,
								  "Before logging out please close all information windows. \nAre you sure you want to logout?",
								  "Logout?",
								  JOptionPane.YES_NO_OPTION);
		if (selectedOption == JOptionPane.YES_OPTION) {
			try{
				manager.logout();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			this.dispose();
			parentWindow.setVisible(true);
			return true;
		} else {
			this.setVisible(true);
			return false;
		}
	}

	private void goToOfflineMode() {
		addPanel.setVisible(false);
		editPanel.setVisible(false);
		removePanel.setVisible(false);
		userMenu.setVisible(false);
		fileMenuViewLogs.setVisible((false));
	}
	/**
	 *
	 * @param mode
	 *  0 runs all clear
	 *  1 - add
	 *  2 - lookup
	 *  3 - edit
	 *  4 - remove
	 */
	private void clearFields(int mode) {
		if(mode == 1 || mode <1) {
			txtserviceAdd.setText("");
			txtusernameAdd.setText("");
			txtpasswordAdd.setText("");
			txtdescriptionAdd.setText("");
		}
		if(mode == 2 || mode <1) {
			txtserviceLookup.setText("");
		}
		if(mode == 3 || mode <1){
			txtserviceEdit.setText("");
		}
		if(mode == 4 || mode <1) {
			txtserviceRemove.setText("");
			txtusernameRemove.setText("");
		}
	}
	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
		/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>
		//</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new SandActionsGUI(null,null,false).setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton addButton;
	private javax.swing.JPanel addPanel;
	private javax.swing.JButton editButton;
	private javax.swing.JPanel editPanel;
	private javax.swing.JMenu fileMenu;
	private javax.swing.JMenuItem fileMenuLogoff;
	private javax.swing.JMenuItem fileMenuViewLogs;
	private javax.swing.JLabel lbldescriptionAdd;
	private javax.swing.JLabel lblpasswordAdd;
	private javax.swing.JLabel lblserviceAdd;
	private javax.swing.JLabel lblserviceEdit;
	private javax.swing.JLabel lblserviceLookup;
	private javax.swing.JLabel lblserviceRemove;
	private javax.swing.JLabel lblusernameAdd;
	private javax.swing.JLabel lblusernameRemove;
	private javax.swing.JButton lookupAllbutton;
	private javax.swing.JButton lookupButton;
	private javax.swing.JPanel lookupPanel;
	private javax.swing.JMenuBar menuBar;
	private javax.swing.JButton removeAllButton;
	private javax.swing.JButton removeButton;
	private javax.swing.JPanel removePanel;
	private javax.swing.JTextField txtdescriptionAdd;
	private javax.swing.JTextField txtpasswordAdd;
	private javax.swing.JTextField txtserviceAdd;
	private javax.swing.JTextField txtserviceEdit;
	private javax.swing.JTextField txtserviceLookup;
	private javax.swing.JTextField txtserviceRemove;
	private javax.swing.JTextField txtusernameAdd;
	private javax.swing.JTextField txtusernameRemove;
	private javax.swing.JMenu userMenu;
	private javax.swing.JMenuItem userMenuEditInfo;
	private javax.swing.JMenuItem userMenuRemoveAccount;
	// End of variables declaration//GEN-END:variables
}
