/**
 * EGroupware - Notifications Java Desktop App
 *
 * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
 * @package notifications
 * @subpackage jdesk
 * @link http://www.egroupware.org
 * @author Stefan Werfling <stefan.werfling@hw-softwareentwicklung.de>
 * @author Maik Hüttner <maik.huettner@hw-softwareentwicklung.de>
 */
package egroupwaretray.settings;

import egroupwaretray.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * egwSettingUrl
 * 
 * @author Stefan Werfling <stefan.werfling@hw-softwareentwicklung.de>
 */
public class egwSettingUrl extends javax.swing.JDialog {

	private jegwconfig _config = null;
	
	/**
	 * Creates new form egwSettingUrl
	 */
	public egwSettingUrl(java.awt.Frame parent, boolean modal, jegwconfig configmanager)
	{
		super(parent, modal);
		initComponents();
		
		this._config = configmanager;
		
		if( this._config.getCXMLM().countConf() > 0 )
		{	
			KeyArray aktivconf = this._config.getCXMLM().getActivConf();

			if( aktivconf != null )
			{
				this.jTextFieldUrl.setText(aktivconf.getString("egwurl"));
			}
		}
		
		this.jButtonNext.setText(jegwConst.getConstTag("egw_txt_next"));
		this.jButtonCancel.setText(jegwConst.getConstTag("egw_txt_cancel"));
		this.jLabelStep.setText(jegwConst.getConstTag("egw_txt_step") + " 1.");
		this.jLabelInfoText.setText(jegwConst.getConstTag("egw_msg_info_url"));
	}

	/**
	 * 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() {

        jLabelStep = new javax.swing.JLabel();
        jLabelInfoText = new javax.swing.JLabel();
        jLabelTitleUrl = new javax.swing.JLabel();
        jTextFieldUrl = new javax.swing.JTextField();
        jButtonNext = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabelStep.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelStep.setText("Schritt 1.");

        jLabelInfoText.setText("Geben Sie bitte die URL zu Ihren Egroupware an, achten Sie auf die");

        jLabelTitleUrl.setText("Egroupware URL:");

        jTextFieldUrl.setText("https://my.domain.de/egroupware/");

        jButtonNext.setText("Weiter");
        jButtonNext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mouseClickedNext(evt);
            }
        });

        jButtonCancel.setText("Abbrechen");
        jButtonCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mouseClickedCancel(evt);
            }
        });

        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)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelTitleUrl)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldUrl))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelStep)
                            .addComponent(jLabelInfoText))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButtonCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonNext)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelStep)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelInfoText)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelTitleUrl)
                    .addComponent(jTextFieldUrl, 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.BASELINE)
                    .addComponent(jButtonNext)
                    .addComponent(jButtonCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

	private void mouseClickedNext(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mouseClickedNext

		this.jButtonCancel.setEnabled(false);
		this.jButtonNext.setEnabled(false);
		
		this.repaint();
		
		String url = this.jTextFieldUrl.getText();
		
		if( url != null )
		{
			jegwhttp egwhttp = new jegwhttp(null);
			
			KeyArray config = null;
			
			if( this._config.getCXMLM().countConf() > 0 )
			{	
				KeyArray aktivconf = this._config.getCXMLM().getActivConf();

				if( aktivconf != null )
				{
					config = aktivconf;
				}
			}
			
			if( config== null )
			{
				// Config erzeugen
				config = new KeyArray(jegwxmlconfig.CONF_STRUCT);
			
				config.add("host", "oneconfig");
			}
			
			// is "/" on end?
			url = jegwhttp.checkDir(url);
			
			config.add("egwurl", url);
			
			try
			{
				String[] domains = egwhttp.getEgwLoginDomains(config);
			  
				if( BaseHttp.getTrustManager() != null )
				{
					// TODO add read out config
					config.add("sslcert", 
						BaseHttp.getTrustManager().getAcceptedCerts());
				}
				
				if( (domains == null) || (domains.length==0) )
				{
					 JOptionPane.showMessageDialog(
						EgroupwareTrayApp.getApplication().getMainFrame(),
						jegwConst.getConstTag("egw_msg_egroupware_not_found"), 
						jegwConst.getConstTag("egw_txt_setting"), 
						JOptionPane.INFORMATION_MESSAGE
						);
				}
				else
				{	
					
					this._config.getCXMLM().deleteConf(0);
					this._config.getCXMLM().addConf(config);
					
					JFrame jf = EgroupwareTrayApp.getApplication().getMainFrame();
					egwSettingDomain dialog = new egwSettingDomain(jf, true, this._config);
					
					dialog.clearSelect();
					
					for( int i=0; i<domains.length; i++ )
					{
						dialog.addSelect(domains[i]);
					}
					
					dialog.updateCombobox();
					
					try {
						dialog.setIconImage(hwTrayIcon.getImage(jegwConst.getConstTag("egwicon")));
					} catch (IOException ex) {
						Logger.getLogger(hwTrayIcon.class.getName()).log(Level.SEVERE, null, ex);
					}

					dialog.setAlwaysOnTop(true);
					dialog.setVisible(true);
					
					if( !dialog.isClickedBack() )
					{
						this.setVisible(false);
					}
				}
			}
			catch( Exception ex )
			{
				Logger.getLogger(egwSettingUrl.class.getName()).log(Level.SEVERE, null, ex);
				
				jegwMain.infoDialog(
					jegwConst.getConstTag("egw_msg_egroupware_not_found_con_lost"),
					jegwConst.getConstTag("egw_txt_setting"));
			}
		}
		
		this.jButtonNext.setEnabled(true);
		this.jButtonCancel.setEnabled(true);
	}//GEN-LAST:event_mouseClickedNext

	private void mouseClickedCancel(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mouseClickedCancel
		
		if( jegwMain.confirmDialog(
			jegwConst.getConstTag("egw_msg_cancal_setting"),
			jegwConst.getConstTag("egw_txt_cancal2") ) == 0 )
		{
			this.setVisible(false);
		}
		
	}//GEN-LAST:event_mouseClickedCancel

	/**
	 * @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(egwSettingUrl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(egwSettingUrl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(egwSettingUrl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(egwSettingUrl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/*
		 * Create and display the dialog
		 */
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				egwSettingUrl dialog = new egwSettingUrl(new javax.swing.JFrame(), true, null);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {

					@Override
					public void windowClosing(java.awt.event.WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonNext;
    private javax.swing.JLabel jLabelInfoText;
    private javax.swing.JLabel jLabelStep;
    private javax.swing.JLabel jLabelTitleUrl;
    private javax.swing.JTextField jTextFieldUrl;
    // End of variables declaration//GEN-END:variables
}
