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

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 java.util.logging.Level;
import java.util.logging.Logger;

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;

/**
 * Dialog to init the parameters for the Lab Talon website. After input press ok-Button to launch the website.
 * It use the class LabTalonIntiPanel how includes all GUI components and input fields.
 * 
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: LabTalonInitDialog.java,v $
 * <br>Revision 1.2  2013-12-27 18:09:27  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.1  2013-07-10 16:28:43  troth
 * <br>Add lab talon button in patient view.
 * <br>
 */
public class LabTalonInitDialog extends GECAMedBaseDialog implements ActionListener, PropertyChangeListener {

	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(LabTalonInitDialog.class.getName());
	
	private LabTalonInitPanel labTalon;
	
	
	public LabTalonInitDialog(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.labTalon = new LabTalonInitPanel();
		this.add(this.labTalon);
		
	}
	
	/**
	 * Show the LabTalon-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")
			)
			{
				labTalon.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(labTalon.getURL(),desktop);
			        }else{
			        	//System.out.println("WARNING: Desktop API doesn't support the browse action, can't launching Browser.");
			        	logger.log(Level.WARNING, "Desktop API doesn't support the browse action, can't launching Browser.");
			        	if(!UrlOpener.openURL(labTalon.getURL()))
						{
							logger.log(Level.WARNING, "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.WARNING, "Desktop API not supported, can't launching Browser.");
			    	if(!UrlOpener.openURL(labTalon.getURL()))
					{
						logger.log(Level.WARNING, "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.WARNING, "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.WARNING, "Can't launching Browser.", use);
        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
        			Translatrix.getTranslationString("medLogin.inputErrorText"),
        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
				    JOptionPane.WARNING_MESSAGE);
        }
    }
}
