import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.io.*;

	 class ventanaDDNS extends JFrame
{
	private		JTabbedPane tabbedPane;
   	private		JPanel		connectionPanel;
   	private		JPanel		statusPanel;
   	private		JPanel		hostPanel, accountPanel, keyPanel,buttonsPanel;
   	private		JPanel		textPanel; 
	private		JTextField	hostnameT = null, usernameT = null, keyT = null;
	private		Choice 		menuDns; 
	private		JPasswordField	fieldPass;
	private		String 		strPass;
	private		JButton 	cancelButton, disconnectButton;
	private 	JTextArea 	statusArea;
	private     boolean bool_noIp;
	private     boolean bool_other;
	private 	Thread t;
	private static		String tiempo;
	public ventanaDDNS() {
		bool_other=false;
		setTitle( "Not Another Dynamic DNS" );
		setSize( 400, 400 );
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JMenuBar menuBar=new JMenuBar();
		JMenu menu= new JMenu("Menu");
		
		JMenuItem item1=new JMenuItem("About");
		item1.addActionListener(
				new ActionListener()
				{
					public void actionPerformed(ActionEvent event) {
						JFrame aboutFrame = new JFrame("About");
						aboutFrame.setSize( 200, 200 );
						JTextPane aboutPane = new JTextPane();
						aboutPane.setEditable(false);
						Font font = new Font("Garamond", Font.PLAIN, 12);
						aboutPane.setFont(font);
						
						String[] initString =	{ "Not Another Dynamic DNS\n\n",
                        "Versión 1.0\nAutores:\nClaudia Codriansky\nFrancisco Castillo\n\n",
                        "Noviembre 2006"
                        };
						
						String[] initStyles ={ "bold", "regular", "italic"};
						
						StyledDocument doc = aboutPane.getStyledDocument();
                  Style def = StyleContext.getDefaultStyleContext().
                     getStyle(StyleContext.DEFAULT_STYLE);
               
                  Style regular = doc.addStyle("regular", def);
                  StyleConstants.setFontFamily(def, "SansSerif");
               
                  Style s = doc.addStyle("italic", regular);
                  StyleConstants.setItalic(s, true);
               
                  s = doc.addStyle("bold", regular);
                  StyleConstants.setBold(s, true);
               	
                  try {
                     for (int i=0; i < initString.length; i++) {
                        doc.insertString(doc.getLength(), initString[i],
                              doc.getStyle(initStyles[i]));
                     }
                  } 
                      catch (BadLocationException ble) {
                        System.err.println("Couldn't insert initial text into text pane.");
                     }
                       	
                  aboutFrame.add(aboutPane);
                  aboutFrame.setVisible(true);
               }   
            });
   	
      JMenuItem item2=new JMenuItem("Exit");
      item2.addActionListener(
             new ActionListener()
            {   
                public void actionPerformed(ActionEvent event)
               {
                  System.exit(0);
               }   
            });
   	
      menu.add(item1);
      menu.add(new JSeparator());
      menu.add(item2);
      menuBar.add(menu);
      setJMenuBar(menuBar);
   
      JPanel topPanel = new JPanel();
      topPanel.setLayout( new BorderLayout() );
      getContentPane().add( topPanel );
   
      createConnectionTab();
      createStatusTab();      
   	      	
      tabbedPane = new JTabbedPane();
      tabbedPane.addTab( "Connection", connectionPanel );
      tabbedPane.addTab( "Status", statusPanel );
      topPanel.add( tabbedPane, BorderLayout.CENTER );
   }

    public void createConnectionTab()
   {
      connectionPanel = new JPanel();
      connectionPanel.setLayout(new BoxLayout(connectionPanel, BoxLayout.Y_AXIS));
      connectionPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
   
      hostPanel=new JPanel();
      hostPanel.setLayout(new GridLayout(2,2));
      hostPanel.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createTitledBorder("Dynamic DNS Server"),
                   BorderFactory.createEmptyBorder(5,5,5,5)));
   
      JLabel dnsName = new JLabel( "DDNS Service: " );
      hostPanel.add( dnsName );
   
			menuDns = new Choice();
      menuDns.addItem("DynDNS.org");
      menuDns.addItem("TZO.com");
      menuDns.addItem("no-ip.com");
      menuDns.addItem("Other");
       
   	hostPanel.add(menuDns);
			
			JLabel hostname = new JLabel( "HostName: " );
      hostPanel.add( hostname );
			hostnameT=new JTextField();
      hostPanel.add(hostnameT);
			
			menuDns.addItemListener(new ItemListener(){
				public void itemStateChanged(ItemEvent event){
					if (event.getItem()=="Other"){ 
						hostnameT.setEnabled(true);
						 
					}else
						if (event.getItem()=="no-ip.com"){
							hostnameT.setEnabled(true);
						}else
							if (event.getItem()=="DynDNS.org"){
								hostnameT.setEnabled(true);
							}else
								if (event.getItem()=="TZO.com"){ 
									hostnameT.setEnabled(true);
						}
						
				}
			});
   			hostnameT.setEnabled(false);
   			accountPanel=new JPanel();
   			accountPanel.setLayout(new GridLayout(2,2));
   			accountPanel.setBorder(BorderFactory.createCompoundBorder(
   					BorderFactory.createTitledBorder("Account Information"),
   					BorderFactory.createEmptyBorder(5,5,5,5)));
   			JLabel username = new JLabel( "Username:" );
   			accountPanel.add( username );
   			usernameT=new JTextField();
   			accountPanel.add(usernameT);
   			
   			JLabel password = new JLabel( "Password:" );
   			accountPanel.add( password );
   			fieldPass = new JPasswordField();
   			accountPanel.add( fieldPass );
   			keyPanel=new JPanel();
   			keyPanel.setLayout(new GridLayout(1,2));
   			keyPanel.setBorder(BorderFactory.createCompoundBorder(
   					BorderFactory.createTitledBorder("Key"),
   					BorderFactory.createEmptyBorder(5,5,5,5)));
   			JLabel key = new JLabel( "Key:" );
   			keyPanel.add( key );
   			keyT=new JTextField();
   			keyPanel.add(keyT);
   			
   			buttonsPanel=new JPanel();
   			buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
 			
			JButton connectButton=new JButton("Connect");
			connectButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent event){
				if (menuDns.getSelectedItem()=="Other"){
				strPass = new String(fieldPass.getPassword());
					if ((hostnameT.getText()==null)||(usernameT.getText()==null)||(strPass==null)||(keyT.getText()==null)){
							JOptionPane.showMessageDialog(null,"Please, fill all the required fields",
 						"Warning: Incomplete Data",JOptionPane.WARNING_MESSAGE);	
						}
						// Los campos estan llenos
						else{
							cancelButton.setEnabled(true);
							
							statusArea.append("\nEstableciendo conexión...");
							
							// Se adquieren los datos
							String act_conf1=usernameT.getText();
							String act_conf2=hostnameT.getText();
							System.out.println(act_conf1);
							System.out.println(act_conf2);
							//URL u = new URL("http", usernameT.getText()+":"+strPass+"@dynupdate.no-ip.com", 
							//		"/nic/update?hostname="+hostnameT.getText());
							// Es la primera vez que entra
							if (bool_other==false)
							{
								bool_other=true;
								
								t = new ManejadorDeAcciones(usernameT.getText(),
										strPass, hostnameT.getText(), tiempo, statusArea);
								t.start();
								
								
								/**
								 * This code creates a URL object that points to
								 * http://lcsaxp.lcs.psu.edu:1212/%3b&db=psu, specifying port 1,212 explicitly. 
								 */
							}else
								{
									if(t.isAlive()){t.destroy();}
									t = new ManejadorDeAcciones(usernameT.getText(),
											strPass, hostnameT.getText(), tiempo, statusArea);
									t.start();
									
								}
							//cuando este la conexion establecida:
							//statusArea.append("\nConexión exitosa!");
							//disconnectButton.setEnabled(true);
						}
					}
						if (menuDns.getSelectedItem()=="no-ip.com"){
						strPass = new String(fieldPass.getPassword());
					if ((hostnameT.getText()==null)||(usernameT.getText()==null)||(strPass==null)||(keyT.getText()==null)){
							JOptionPane.showMessageDialog(null,"Please, fill all the required fields",
 						"Warning: Incomplete Data",JOptionPane.WARNING_MESSAGE);	
						}
						// Los campos estan llenos
						else{
							cancelButton.setEnabled(true);
							statusArea.append("\nEstableciendo conexión...");
							System.out.println(usernameT.getText()+":"+strPass+"@dynupdate.no-ip.com");
								
							try {
									URL u = new URL("http", usernameT.getText()+":"+strPass+"@dynupdate.no-ip.com", 
										"/nic/update?hostname="+hostnameT.getText());
								}
								catch (MalformedURLException e) {
								// All VMs should recognize http
								}
							//realizar conexion
							
							//cuando este la conexion establecida:
							//statusArea.append("\nConexión exitosa!");
							//disconnectButton.setEnabled(true);
						}
					}
					
					
					
					else{
						if ((usernameT.getText()=="")||(strPass=="")||(keyT.getText()=="")){
							JOptionPane.showMessageDialog(null,"Please, fill all the required fields",
 						"Warning: Incomplete Data",JOptionPane.WARNING_MESSAGE);		
						}
						else{
							cancelButton.setEnabled(true);
							statusArea.append("\nEstableciendo conexión...");
							//realizar conexion
							//cuando este la conexion establecida:
							//statusArea.append("\nConexión exitosa!");
							//disconnectButton.setEnabled(true);
						}
					}					
				}
			});
      JButton clearButton=new JButton("Clear");
			clearButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent event){
					hostnameT.setText("");
					usernameT.setText("");
					fieldPass.setText("");
					keyT.setText("");
				}
			});
      cancelButton=new JButton("Cancel");
			cancelButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent event){
					cancelButton.setEnabled(false);
					statusArea.append("\nIntento de conexión cancelado por el usuario!");
					//cancelar intento de conexion
				}
			});
			cancelButton.setEnabled(false);
			/*
		disconnectButton=new JButton("Disconnect");
			disconnectButton.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent event){
					disconnectButton.setEnabled(false);
					statusArea.append("\nConexión cerrada por el usuario");
					//cerrar conexion
				}
			});
			disconnectButton.setEnabled(false);      
			*/
			buttonsPanel.add(connectButton);
      buttonsPanel.add(clearButton);
      buttonsPanel.add(cancelButton);
			//buttonsPanel.add(disconnectButton);			
   
      connectionPanel.add(hostPanel);
      connectionPanel.add(accountPanel);
      connectionPanel.add(keyPanel);
      connectionPanel.add(buttonsPanel);
   
   }

    public void createStatusTab()
   {
      statusPanel = new JPanel();
      statusPanel.setLayout( new BorderLayout() );
   
      textPanel=new JPanel();
      textPanel.setLayout(new GridLayout(1,2));
      textPanel.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createTitledBorder("Status"),
                   BorderFactory.createEmptyBorder(5,5,5,5)));
   
      statusArea=new JTextArea("Probando el textArea de status...");
      statusArea.setFont(new Font("Courier New", Font.PLAIN, 11));
      statusArea.setLineWrap(true);
      statusArea.setWrapStyleWord(true);
      statusArea.setEditable(false);
      JScrollPane scrollPane = new JScrollPane(statusArea);
      textPanel.add(scrollPane);      
			
			statusPanel.add(textPanel);
   
   }
	
   public static void main( String args[] )
   {
      ventanaDDNS mainFrame	= new ventanaDDNS();
      ventanaDDNS.tiempo = args[0];
      mainFrame.setVisible(true);
      
   }
   public static final long serialVersionUID = 1L;

}
	 class ManejadorDeAcciones extends Thread
	 { 
	 /**
	    Constructs a handler.
	    @param i the incoming socket
	    @param c the counter for the handlers (used in prompts)
	 */
	 	
	 	private String t;
	 	private JTextArea statusArea;
	 	private String hostname;
	 	private String user;
	 	private String pass;
	 	long tie;
	 	public ManejadorDeAcciones(String user,String pass,String hostname, String t, JTextArea area)
	 	{
	 		 
	 		
	 		int numInt=Integer.valueOf(t).intValue();
	 		tie = (long) (numInt * 1000);
	 		this.user = user;
	 		this.pass = pass;
	 		this.hostname = hostname;
	 		statusArea = area;
	 		
	 	}
	 	public void run()
	 	{
			try
			{
				while(true)
				{
					// Creo el socket de conexion
					Socket s = new Socket(hostname, 7777);
					BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
					PrintWriter out2 = new PrintWriter(s.getOutputStream(), true /* autoFlush */);
					
					out2.println(user);
					out2.println(pass);
					out2.println(hostname);
					this.sleep(tie);
					s.close();
				}
			}// Fin try
			catch (IOException e)
			{
				e.printStackTrace();
				} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	 	
	 	}

	 }