/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software is distributed in the hope that it will be useful, but     *
 *  WITHOUT ANY WARRANTY; without even the implied warranty of               *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
 *  Lesser General Public License for more details.                          *
 *                                                                           *
 *  You should have received a copy of the GNU Lesser General Public         *
 *  License along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.patient.gui.cyberlabKetterthill;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.ExternalPasswordStore;
import lu.tudor.santec.gecamed.core.ejb.session.beans.ExternalPasswordStoreBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.ExternalPasswordStoreInterface;
import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.IconFetcher;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.GecamedUser;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * Panel to enter the settings (physician and the password) for Cyberlab Ketterthill.
 * 
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: CyberlabInitPanel.java,v $
 * <br>Revision 1.8  2013-12-27 18:08:04  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.7  2013-07-15 06:18:34  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.6  2013-02-19 12:07:34  ferring
 * <br>GECAMedLists changed. Will now automatically load list of all beans
 * <br>
 * <br>Revision 1.5  2012-08-07 14:00:18  troth
 * <br>Add function to allow users to delete the login informations in the new table external password store.
 * <br>
 * <br>Revision 1.4  2012-08-06 14:52:13  troth
 * <br>Now the Cyberlab service stores the tokens of the users in the new table external password store.
 * <br>
 * <br>Revision 1.3  2012-08-01 15:38:02  troth
 * <br>Remove token and password saving in the database for MedLogin and CyberLab. Now the token and password is only save for one GECAMed session.
 * <br>
 * <br>Revision 1.2  2012-07-13 13:31:34  troth
 * <br>Implementation of Ticket #1003 - Some little changes.
 * <br>
 * <br>Revision 1.1  2012-07-12 15:50:32  troth
 * <br>Implementation of Ticket #1003.
 * <br>
 */
public class CyberlabInitPanel extends JPanel{

	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(CyberlabInitPanel.class.getName());

	/**
	 * Need GUI Components
	 */
	// Logo & Icon
	private JLabel logoLabel;
	
	private Icon icon;

	// Loginname
	private JLabel loginNameLabel;
	
	private JTextField loginNameField;
	
	// Password
	private JLabel passwordLabel;

	private JPasswordField passwordField;

	// Physician
	private JLabel physicianLabel;

	private JComboBox physicianBox;
	
	private Boolean enableComboboxActionListener = true;
		
	// Ordernumber
	private JLabel numberLabel;

	private JTextField numberField;

	// Save password in database
	private JCheckBox savePasswordCheckBox;
	
	private Boolean savePassword = false;
	
	private ExternalPasswordStore currentPassword;
	
	private ExternalPasswordStore currentLogin;
	
	private static String passwordType = "CyberLab";
	
	private static String passwordKey = "Password";
	
	private static String loginKey = "LoginName";
	
	/**
	 * Needed Objects 
	 */
	private Physician currentPhysician;
	
	private Patient currentPatient;

	private GecamedUser currentUser;


	/**
	 * Needed beans
	 */
	private static ExternalPasswordStoreInterface passwordManager;
	
	/**
	 * Initialize all needed beans
	 */
	static
	{
		try{
			passwordManager = (ExternalPasswordStoreInterface) ManagerFactory.getRemote(ExternalPasswordStoreBean.class);
		} catch (Exception e) {
			logger.log(Level.WARN, "Couldn't get connection with ExternalPasswordStoreBean.", e);
		}
	}
	
	/**
	 * The Constructor init all GUI Components. There are two layouts one for the user with permission for Cyberlab Ketterthill and one for the user without this permission.
	 */
	public CyberlabInitPanel()
	{
		if(
				PatientManagerModule.getCurrentUser().getPhysicians().size() > 0
				|| GECAMedModule.userHasPermission("Core.changePhysician")
//				|| GECAMedModule.userHasRole("PatientModule", "physician")
		)
		{
			// -------------------------------------------------------
			// The panel layout (FormLayout) (User with permissions)
			// -------------------------------------------------------
			CellConstraints cc = new CellConstraints();
			this.setLayout(new FormLayout(
					// cols
					"10dlu," +			// 1
					"fill:pref," + 		// 2 left
					"3dlu," +			// 3
					"fill:pref," + 		// 4 right
					"10dlu",			// 5
					// rows
					"10dlu," +			// 1
					"fill:pref," +		// 2 logo
					"6dlu," +			// 3
					"fill:pref," +		// 4 physician
					"6dlu," +			// 5
					"fill:pref," +		// 6 loginname
					"6dlu," +			// 7
					"fill:pref," +		// 8 password
					"6dlu," +			// 9
					"fill:pref," +		// 10 number
					"6dlu," +			// 11
					"fill:pref," +		// 12 checkbox savepassword
					"10dlu"				// 13
					));
			this.setOpaque(false);
			
			// -------------------------------------------------------
			// logo
			// -------------------------------------------------------
			icon = new ImageIcon(IconFetcher.getIcon(PatientManagerModule.class, PatientManagerModule.CYBERLAB).getImage());
			this.logoLabel = new JLabel(icon);
	
			// -------------------------------------------------------
			// physician
			// -------------------------------------------------------
			this.physicianLabel = new JLabel(Translatrix.getTranslationString("cyberlabKetterthill.physicianLabel") + " :");
			this.physicianLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			this.physicianBox = new JComboBox();
			
			// init physician select box
			refreshPhysicianBox();
			
			// add listener to physician select box
			this.physicianBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if (enableComboboxActionListener) 
					{
//						currentPhysician = ((Physician) physicianBox.getSelectedItem());
//						loginNameField.setText(currentPhysician.getCyberlabLoginName());
//						passwordField.setText(PatientPanel.getCyberlabPassword(currentPhysician.getId()));
//						
//						if(PatientManagerModule.getCurrentUser().getPhysicians().contains(currentPhysician))
//						{ 
//							loginNameField.setEnabled(true);
//							passwordField.setEnabled(true);
//						}else{ 
//							loginNameField.setEnabled(false);
//							passwordField.setEnabled(false);
//						}
						currentUser = PatientManagerModule.getCurrentUser();
						currentPhysician = ((Physician) physicianBox.getSelectedItem());
						// get loginname
						try {
							currentLogin = passwordManager.getPassword(currentPhysician.getId(), passwordType, loginKey);
							
							if(currentLogin != null)
							{
								loginNameField.setText(currentLogin.getValue());
								savePassword = true;
							}else{
								loginNameField.setText("");
								savePassword = false;
								currentLogin = new ExternalPasswordStore();
								currentLogin.setUserId(currentUser.getId());
								currentLogin.setPhysicianId(currentPhysician.getId());
								currentLogin.setType(passwordType);
								currentLogin.setKey(loginKey);
							}
							savePasswordCheckBox.setSelected(savePassword);
							
						} catch (Exception e1) {
							logger.log(Level.WARN, "Couldn't load loginname from database table core.external_password_store.", e1);
							e1.printStackTrace();
						}
						// get password
						try {
							currentPassword = passwordManager.getPassword(currentPhysician.getId(), passwordType, passwordKey);
							
							if(currentPassword != null)
							{
								passwordField.setText(currentPassword.getValue());
								savePassword = true;
							}else{
								loginNameField.setText("");
								passwordField.setText("");
								savePassword = false;
								currentPassword = new ExternalPasswordStore();
								currentPassword.setUserId(currentUser.getId());
								currentPassword.setPhysicianId(currentPhysician.getId());
								currentPassword.setType(passwordType);
								currentPassword.setKey(passwordKey);
							}
							savePasswordCheckBox.setSelected(savePassword);
							
						} catch (Exception e1) {
							logger.log(Level.WARN, "Couldn't load password from database table core.external_password_store.", e1);
							e1.printStackTrace();
						}
						if(PatientManagerModule.getCurrentUser().getPhysicians().contains(currentPhysician))
						{
							loginNameField.setEnabled(true);
							passwordField.setEnabled(true);
							savePasswordCheckBox.setEnabled(true);
						}else{
							loginNameField.setEnabled(false);
							passwordField.setEnabled(false);
							savePasswordCheckBox.setEnabled(false);
						}
					}
				}
			});
			
			// -------------------------------------------------------
			// password
			// -------------------------------------------------------
			this.loginNameLabel = new JLabel(Translatrix.getTranslationString("cyberlabKetterthill.loginNameLabel") + " :");
			this.loginNameLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			this.loginNameField = new JTextField(40);
			this.loginNameField.setToolTipText(Translatrix.getTranslationString("cyberlabKetterthill.loginNameTooltip"));
			
			// -------------------------------------------------------
			// password
			// -------------------------------------------------------
			this.passwordLabel = new JLabel(Translatrix.getTranslationString("cyberlabKetterthill.passwordLabel") + " :");
			this.passwordLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			this.passwordField = new JPasswordField(40);
			this.passwordField.setToolTipText(Translatrix.getTranslationString("cyberlabKetterthill.passwordTooltip"));
			
			// -------------------------------------------------------
			// order number
			// -------------------------------------------------------
			this.numberLabel = new JLabel(Translatrix.getTranslationString("cyberlabKetterthill.orderNumberLabel") + " :");
			this.numberLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			this.numberField = new JTextField(40);
			this.numberField.setToolTipText(Translatrix.getTranslationString("cyberlabKetterthill.orderNumberTooltip"));
			
			// -------------------------------------------------------
			// save password check box
			// -------------------------------------------------------
			this.savePasswordCheckBox = new JCheckBox(Translatrix.getTranslationString("cyberlabKetterthill.savePasswordLabel"));
			this.savePasswordCheckBox.addActionListener(new ActionListener() {
				
				public void actionPerformed(ActionEvent e)
				{
					if(savePassword) savePassword = false;
					else savePassword = true;
				}
			});
			
			// -------------------------------------------------------
			// add components to panel
			// -------------------------------------------------------
			this.add(this.logoLabel, 			cc.xyw	(2, 2, 3));
			this.add(this.physicianLabel,		cc.xy	(2, 4));
			this.add(this.physicianBox, 		cc.xy	(4, 4));
			this.add(this.loginNameLabel, 		cc.xy	(2, 6));
			this.add(this.loginNameField,		cc.xy	(4, 6));
			this.add(this.passwordLabel, 		cc.xy	(2, 8));
			this.add(this.passwordField, 		cc.xy	(4, 8));
			this.add(this.numberLabel, 			cc.xy	(2, 10));
			this.add(this.numberField, 			cc.xy	(4, 10));
			this.add(this.savePasswordCheckBox, cc.xyw 	(2, 12, 3));
			
			// get current user
			currentUser = PatientManagerModule.getCurrentUser();
			// get current physician
			currentPhysician = PatientManagerModule.getCurrentPhysician();
			this.enableComboboxActionListener = false;
			this.physicianBox.setSelectedItem(currentPhysician);
			this.enableComboboxActionListener = true;
			// set loginname
			try {
				currentLogin = passwordManager.getPassword(currentPhysician.getId() ,passwordType ,loginKey);
				if(currentLogin != null)
				{
					this.loginNameField.setText(currentLogin.getValue());
					savePassword = true;
				}else{
					this.loginNameField.setText("");
					savePassword = false;
					currentLogin = new ExternalPasswordStore();
					currentLogin.setUserId(currentUser.getId());
					currentLogin.setPhysicianId(currentPhysician.getId());
					currentLogin.setType(passwordType);
					currentLogin.setKey(loginKey);
				}
				
			} catch (Exception e1) {
				logger.log(Level.WARN, "Couldn't load loginname from database table core.external_password_store.", e1);
				e1.printStackTrace();
			}
			if(PatientManagerModule.getCurrentUser().getPhysicians().contains(currentPhysician))
			{
				loginNameField.setEnabled(true);
				savePasswordCheckBox.setEnabled(true);
			}else{
				loginNameField.setEnabled(false);
				savePasswordCheckBox.setEnabled(false);
			}
			
			// set password
			try {
				currentPassword = passwordManager.getPassword(currentPhysician.getId() ,passwordType ,passwordKey);
				if(currentPassword != null)
				{
					this.passwordField.setText(currentPassword.getValue());
					savePassword = true;
				}else{
					this.passwordField.setText("");
					savePassword = false;
					currentPassword = new ExternalPasswordStore();
					currentPassword.setUserId(currentUser.getId());
					currentPassword.setPhysicianId(currentPhysician.getId());
					currentPassword.setType(passwordType);
					currentPassword.setKey(passwordKey);
				}
				
			} catch (Exception e1) {
				logger.log(Level.WARN, "Couldn't load password from database table core.external_password_store.", e1);
				e1.printStackTrace();
			}
			if(PatientManagerModule.getCurrentUser().getPhysicians().contains(currentPhysician))
			{
				passwordField.setEnabled(true);
				savePasswordCheckBox.setEnabled(true);
			}else{
				passwordField.setEnabled(false);
				savePasswordCheckBox.setEnabled(false);
			}
			
			// set current patient
			currentPatient = PatientManagerModule.getCurrentPatient();
		}else{
			// -------------------------------------------------------
			// laylout if user have no permissions
			// -------------------------------------------------------
			CellConstraints cc = new CellConstraints();
			this.setLayout(new FormLayout(
					// cols
					"10dlu," +			// 1
					"fill:pref," + 		// 2 center
					"10dlu",			// 5
					// rows
					"10dlu," +			// 1
					"fill:pref," +		// 2 logo
					"6dlu," +			// 3
					"fill:pref," +		// 4 message
					"10dlu"				// 9
					));
			this.setOpaque(false);
			
			// -------------------------------------------------------
			// logo
			// -------------------------------------------------------
			icon = new ImageIcon(IconFetcher.getIcon(PatientManagerModule.class, PatientManagerModule.CYBERLAB).getImage());
			this.logoLabel = new JLabel(icon);
			
			// -------------------------------------------------------
			// message label
			// -------------------------------------------------------
			this.numberLabel = new JLabel(Translatrix.getTranslationString("cyberlabKetterthill.accessDenied"));
			this.numberLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
						
			// -------------------------------------------------------
			// add components to panel
			// -------------------------------------------------------
			this.add(this.logoLabel, 	cc.xy (2, 2));
			this.add(this.numberLabel, 	cc.xy (2, 4));
		}
		
		// set patient matricule from open patient
		if(currentPatient != null)
			if(!currentPatient.getSocialSecurityNumber().equals("00000000000"))
			{
				this.numberField.setText(currentPatient.getSocialSecurityNumber());
			}
	}
	
	/**
	 * Save the loginname and password of the selected physician or delete it if savePassword is false (flag from the checkbox).
	 */
	public void updateLoginNameAndPassword()
	{
		if(savePassword)
		{
			// save loginname
			currentLogin.setValue(new String(this.loginNameField.getText()));
			try {
				currentLogin = passwordManager.savePassword(currentLogin);
			} catch (Exception e) {
				logger.log(Level.WARN, "Couldn't save loginname in database table core.external_password_store.", e);
			}
			
			// save password
			currentPassword.setValue(new String(this.passwordField.getPassword()));
			try {
				currentPassword = passwordManager.savePassword(currentPassword);
			} catch (Exception e) {
				logger.log(Level.WARN, "Couldn't save password in database table core.external_password_store.", e);
			}
		}else{
			// delete loginname
			try {
				passwordManager.deletePassword(currentLogin);
				currentPassword = null;
			} catch (Exception e) {
				logger.log(Level.WARN, "Couldn't delete loginname in database table core.external_password_store.", e);
			}
			
			// delete password
			try {
				passwordManager.deletePassword(currentPassword);
				currentPassword = null;
			} catch (Exception e) {
				logger.log(Level.WARN, "Couldn't delete password in database table core.external_password_store.", e);
			}
		}
		
//		currentPhysician = (Physician) this.physicianBox.getSelectedItem();	
//		PatientPanel.setCyberlabPassword(currentPhysician.getId(), new String(this.passwordField.getPassword()));
//		
//		currentPhysician.setCyberlabLoginName(this.loginNameField.getText());
//		
//		try {
//			officeManager.savePhysician(currentPhysician);
//		} catch (Exception e) {
//			logger.log(Level.WARN, "Couldn't save Physician.", e);
//			e.printStackTrace();
//		}
	}

	/**
	 * Create and returns a string url of the Cyberlab Ketterthill website with all parameters given from the dialog.
	 * @return a string url of the Cyberlab Ketterthill website
	 */
	public String getURL()
	{
		// create Cyberlab-Ketterthill-URL
		String cyberlabURL = "https://resultats.ketterthill.lu/cyberlab/servlet/be.mips.cyberlab.web.APIEntry?Class=Patient&Method=ViewReport";
		String loginName = "";
		String password = "";
		String object = "";
		
		// set login name
		if(!this.loginNameField.getText().equals(""))
		{
			loginName = "&LoginName=" + this.loginNameField.getText().trim();
		}
		
		// set Password
		if(!new String(this.passwordField.getPassword()).equals(""))
		{
			password = "&Password=" + new String(this.passwordField.getPassword()).trim();
		}
		
		// get patient matricule (Social Security Number) from inpufield
		if(!this.numberField.getText().equals(""))
		{ 
			object = "&Object=" + numberField.getText().trim();
		}
		
		cyberlabURL = cyberlabURL + loginName + password + object;
		cyberlabURL = cyberlabURL + "&OnClose=https://www.llam.lu&Application=HTML_RC";
		
		return cyberlabURL;
	}
	
	/**
	 * Refresh the physician combobox.
	 */
	private void refreshPhysicianBox() {
		// get physician from GECAMedLists
		List<Physician> physicianList = GECAMedLists.getListReference(Physician.class);
		
		this.enableComboboxActionListener = false;
		this.physicianBox.removeAllItems();

		if (physicianList.size() > 0)
			for (Physician physician : physicianList)
			{
				// if user hat the permission to change physician add all physician
				if(GECAMedModule.userHasPermission("Core.changePhysician"))
					this.physicianBox.addItem(physician);
				// else add only the physician which are related to the user
				else
					if(PatientManagerModule.getCurrentUser().getPhysicians().contains(physician))
						this.physicianBox.addItem(physician);
			}
		this.enableComboboxActionListener = true;
	}
}