/*****************************************************************************
 *                                                                           *
 *  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.medLogin;

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 inti the parameters for the MedLogin website and after press ok-Button launch this website. It use the class MedLoginIntiPanel how includes all GUI components and input fields.
 * 
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: MedLoginInitDialog.java,v $
 * <br>Revision 1.14  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.13  2013-07-15 06:18:37  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.12  2013-07-02 09:27:09  ferring
 * <br>Browsing URL changed
 * <br>
 * <br>Revision 1.11  2013-01-15 08:04:34  ferring
 * <br>keep compatibility to Java 1.5
 * <br>
 * <br>Revision 1.10  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.9  2012-08-02 16:14:15  troth
 * <br>Add new table to database for external password store (for MedLogin and other Services).
 * <br>
 * <br>Revision 1.8  2012-07-12 15:50:31  troth
 * <br>Implementation of Ticket #1003.
 * <br>
 * <br>Revision 1.7  2012-04-12 13:50:26  troth
 * <br>Add function to check java version.
 * <br>
 * <br>Revision 1.6  2012-03-07 12:21:02  troth
 * <br>Finish the new function of the MedLogin Button.
 * <br>
 * <br>Revision 1.5  2012-03-06 16:21:14  troth
 * <br>Finish the new function of the MedLogin Button.
 * <br>
 * <br>Revision 1.4  2012-03-05 16:44:25  troth
 * <br>First version of the MedLogin Button.
 * <br>
 * <br>Revision 1.3  2012-03-05 10:35:57  troth
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2012-03-05 09:55:05  troth
 * <br>Test: Open browser over java desktop API.
 * <br>
 * <br>Revision 1.1  2012-02-23 17:06:45  troth
 * <br>Add new dialog to edit the MedLogin physician settings.
 * <br>
 */
public class MedLoginInitDialog extends GECAMedBaseDialog implements ActionListener, PropertyChangeListener {

	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(MedLoginInitDialog.class.getName());
	
	private MedLoginInitPanel medLoginPanel;
	
	
	public MedLoginInitDialog(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.medLoginPanel = new MedLoginInitPanel();
		this.add(this.medLoginPanel);
		
	}
	
	/**
	 * Show the MedLogin-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")
			)
			{
				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)) {
			        	medLoginPanel.updateToken();
			        	
			        	// launch browser
			        	onLaunchBrowser(medLoginPanel.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(medLoginPanel.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(medLoginPanel.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.inputErrorText"),
        			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);
        }
    }
}
