/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginWindow.java
 *
 * Created on Oct 6, 2012, 9:10:14 PM
 */

package basicslick.client;

import java.net.*;
import java.io.*;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ubuntu
 */
public class LoginWindow extends javax.swing.JFrame
{


    ObjectInputStream Sinput;   // to read the socker
    ObjectOutputStream Soutput; // to write on the socket
    Socket socket;    
    boolean connected = false;
    
    String HOSTIP;
    final int PORT;

    

    /** Creates new form LoginWindow */
    public LoginWindow (int port)
    {
        PORT = port;
	initComponents ();
        getIP();
    }
    
    //Find Servers on your network
    //-----------------------------------------------      
    public Socket findServer(){
        
        String IP = getIP();

	String[] nodes = IP.split ("\\D");
	String newIP = "";
	for (int i = 0 ; i < nodes.length - 1 ; i++)
	{
	    newIP = newIP.concat (nodes [i] + ".");	    
	}
        
        //Declares an array used for searching for a server
	Socket[] sktarr = new Socket [255];
	//Search variable
	int i = 0;
	//Search loop
	for (; i < 254 ;)
	{
	    sktarr [i] = new Socket ();
	    try
	    {
		sktarr [i].connect (new InetSocketAddress (newIP + i, PORT), 10);
		return sktarr[i];
	    }
	    catch (IOException ex)
	    {
		i++;
	    }
	}
        return null;	
    }
    
    //Find your network IP address
    //-----------------------------------------------      
    public String getIP(){
        if(HOSTIP != null){
            return HOSTIP;
        }
        else
        {
            try {
                for (
                    final Enumeration< NetworkInterface > interfaces =
                        NetworkInterface.getNetworkInterfaces( );
                    interfaces.hasMoreElements( );
                )
                {
                    final NetworkInterface cur = interfaces.nextElement( );

                    if ( cur.isLoopback( ) )
                    {
                        continue;
                    }

                    for ( final InterfaceAddress addr : cur.getInterfaceAddresses( ) )
                    {
                        final InetAddress inet_addr = addr.getAddress( );
                        if ( !( inet_addr instanceof Inet4Address ) )
                        {
                            continue;
                        }

                        HOSTIP = inet_addr.getHostAddress();
                        System.out.println("address: " + HOSTIP);
                        
                        jTextField3.setText("Your IP: " + HOSTIP);                        
                        return HOSTIP;
                    }
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            } 
        }
        
        //default case
        return "";        
    }

    //Connect to a server on your network
    //-----------------------------------------------     
    public boolean connect (String IP, boolean scan)
    {   
	try
	{
            if(scan){
                socket = findServer();
                if(socket == null){                            
                    jTextField2.setText("Status: No Server Found");	  
                    return false;
                }
            }
            else{
                socket = new Socket();
                socket.connect (new InetSocketAddress (IP, PORT), 10);
            }
	}
	catch (Exception e)
	{
	    System.out.println ("Error connectiong to server:" + e);
	    return false;
	}
	System.out.println ("Connection accepted " +
		socket.getInetAddress () + ":" +
		socket.getPort ());

	/* Creating both Data Stream */
	try
	{
	    Sinput = new ObjectInputStream (socket.getInputStream ());
	    Soutput = new ObjectOutputStream (socket.getOutputStream ());
	}
	catch (IOException e)
	{
	    System.out.println ("Exception creating new Input/output Streams: " + e);
	    return false;
	}

        connected = true;
        return true;
    }


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

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jTextField4 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");

        jButton1.setText("LanScan");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Username:");

        jTextField2.setText("Status: Ready");

        jLabel2.setText("Password:");

        jLabel3.setText("Manual Connection");

        jButton2.setText("Start Server");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField3.setEditable(false);
        jTextField3.setText("Your IP:");

        jButton3.setText("Connect ");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTextField4.setText("Enter Server IP");

        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)
                    .addComponent(jTextField2)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPasswordField1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)))
                    .addComponent(jTextField3)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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


    private void jButton1ActionPerformed (java.awt.event.ActionEvent evt)
    {//GEN-FIRST:event_jButton1ActionPerformed
	// TODO add your handling code here:        
         
        loginthread logthread = new loginthread();             
        logthread.IP = getIP();  
        logthread.scan = true;
        logthread.start();        
	
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
               
        loginthread logthread = new loginthread(); 
        logthread.IP = jTextField4.getText();        
        logthread.scan = false;
        logthread.start();
        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        final Thread serverThread = new Thread(){        
            public void run(){            
                basicslick.server.GameServer server = new basicslick.server.GameServer(PORT);                
            }    
        };        
        serverThread.start(); 
        
    }//GEN-LAST:event_jButton2ActionPerformed


    public boolean login(){
        String Username = jTextField1.getText();
        String Password = String.valueOf(jPasswordField1.getPassword());

        String reply = "";

        try
	{
	    Soutput.writeObject("login " + Username + " " + Password);
	    Soutput.flush ();
	}
	catch (IOException e)
	{
	    System.out.println ("Error writting to the socket: " + e);
            return false;
	}

        try
	{
	    reply =  (String)Sinput.readObject ();
	}
	catch (Exception e)
	{
            System.out.println("login error");
	    System.out.println ("Error reading from the socket: " + e);
            return false;	    
	}

        if (!reply.equals("loggedin")) {
            return false;
        }

        //Perform post-login actions         
                
        final String accepted = Username;
        
        Thread gameThread = new Thread(){        
            public void run(){            
                basicslick.GameFrame.createNetGame(socket,  Soutput, Sinput, accepted);  
            }    
        };
        gameThread.start();      
        
        dispose();
        return true;
    }

    /**
    * @param args the command line arguments
    */
    public static void main (String args[])
    {
	java.awt.EventQueue.invokeLater (new Runnable ()
	{
	    public void run ()
	    {
		new LoginWindow (1500).setVisible (true);
	    }
	}
	);
    }
    
    class loginthread extends Thread{
        String IP;
        Boolean scan;
        public void run(){
            if(!connected){
                if(connect (IP,scan)){
                    if(!login()) {
                        jTextField2.setText("Status: Login Failed");
                    }
                }
                    
            }
        }
    };   
    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables

}
