/*****************************************************************************
 *                                                                           *
 *  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.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JOptionPane;

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.UrlOpener;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.utils.VersionUtils;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * Dialog to init the parameters for the CyberLab Ketterthill website. After input press ok-Button to launch the website.
 * It use the class CyberlabIntiPanel how includes all GUI components and input fields.
 * 
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: CyberlabInitDialog.java,v $
 * <br>Revision 1.9  2013-12-27 18:08:03  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.8  2013-07-15 06:18:34  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.7  2013-07-09 11:26:44  troth
 * <br>Change libs serializer.jar and xalan.jat form 2.7.0 to 2.7.1.
 * <br>
 * <br>Revision 1.6  2013-07-02 09:27:09  ferring
 * <br>Browsing URL changed
 * <br>
 * <br>Revision 1.5  2013-01-15 08:04:34  ferring
 * <br>keep compatibility to Java 1.5
 * <br>
 * <br>Revision 1.4  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.3  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.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:31  troth
 * <br>Implementation of Ticket #1003.
 * <br>
 */
public class CyberlabInitDialog extends GECAMedBaseDialog implements ActionListener, PropertyChangeListener {

	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(CyberlabInitDialog.class.getName());
	
	private CyberlabInitPanel cyberlabPanel;
	
	
	public CyberlabInitDialog(String title, boolean createOkButton,
			boolean createCancelButton)
	{
		super(title, createOkButton, createCancelButton);
		initDialog();
	}
	
	/**
	 * Init the Dialog with all the panels.
	 */
	public void initDialog()
	{
		this.okButton.addActionListener(this);
		this.cancelButton.addActionListener(this);
		this.cyberlabPanel = new CyberlabInitPanel();
		this.add(this.cyberlabPanel);
		
	}
	
	/**
	 * Show the Cyberlab-Dialog to open the default system web-browser with a special link.
	 */
	public void showDialog()
	{	
		pack();
		MainFrame.showDialogCentered(this);	
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 * 
	 * The actions for the ok and cancel button.
	 */
	public void actionPerformed(ActionEvent e)
	{
		// ok button action
		if (e.getSource().equals(this.okButton))
		{
			if(
					PatientManagerModule.getCurrentUser().getPhysicians().size() > 0
					|| GECAMedModule.userHasPermission("Core.changePhysician")
//					|| GECAMedModule.userHasRole("PatientModule", "physician")
			)
			{
				cyberlabPanel.updateLoginNameAndPassword();
				java.awt.Desktop desktop = null;
			    // Before more Desktop API is used, first check 
			    // whether the API is supported by this particular 
			    // virtual machine (VM) on this particular host.
			    //if (Desktop.isDesktopSupported())
			    if(VersionUtils.isSmallerJavaVersionThan(6))
				{
			        desktop = java.awt.Desktop.getDesktop();
			        if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
//			        	cyberlabPanel.saveLoginNameAndPassword();
			        	
			        	// launch browser
			        	onLaunchBrowser(cyberlabPanel.getURL(),desktop);
			        }else{
			        	//System.out.println("WARNING: Desktop API doesn't support the browse action, can't launching Browser.");
			        	logger.log(Level.WARN, "Desktop API doesn't support the browse action, can't launching Browser.");
			        	if (!UrlOpener.openURL(cyberlabPanel.getURL()))
			        	{
							logger.log(Level.WARN, "ERROR: Launching Browser.");
							JOptionPane.showMessageDialog(MainFrame.getInstance(),
								    "Can't launching the default system Browser",
								    "Error: Launching Browser",
								    JOptionPane.WARNING_MESSAGE);
						}
			        }
			    }else{
			    	//System.out.println("WARNING: Desktop API not supported, can't launching Browser.");
			    	logger.log(Level.WARN, "Desktop API not supported, can't launching Browser.");
			    	
			    	if(!UrlOpener.openURL(cyberlabPanel.getURL()))
			    	{
						logger.log(Level.WARN, "ERROR: Launching Browser.");
						JOptionPane.showMessageDialog(MainFrame.getInstance(),
							    "Can't launching the default system Browser",
							    "Error: Launching Browser",
							    JOptionPane.WARNING_MESSAGE);
					}
			    }
		    }

		}
		// cancel button action
		if (e.getSource().equals(this.cancelButton)) {}
	}
	
	/* (non-Javadoc)
	 * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
	 * TODO: Not use jet but maybe use it for if the panel is filled right the ok-Button turn to enabled and the user can press it.
	 */
	public void propertyChange(PropertyChangeEvent evt) {
		
		if(evt.getPropertyName().equals("")){}
	}
	
	/**
	 * Starts the default system web-browser over the desktop API (Java 1.6) and open the given url.
	 * @param url - the url to open in the web-browser
	 * @param desktop - handle to desktop object
	 */
	private void onLaunchBrowser(String url, java.awt.Desktop desktop) {
        URI uri = null;
        try {
            uri = new URI(url);
            desktop.browse(uri);
        }
        catch(IOException ioe) {
        	logger.log(Level.WARN, "Can't launching Browser.", ioe);
        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
        			Translatrix.getTranslationString("medLogin.inuptErrorText"),
        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
				    JOptionPane.WARNING_MESSAGE);
        }
        catch(URISyntaxException use) {
        	logger.log(Level.WARN, "Can't launching Browser.", use);
        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
        			Translatrix.getTranslationString("medLogin.inputErrorText"),
        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
				    JOptionPane.WARNING_MESSAGE);
        }
    }
}
