/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * client.java
 *
 * Created on 03/12/2011, 03:43:33 ã
 */
package chat;
import java.io.*;
import java.net.*;
import javax.swing.DefaultListModel;
import javax.swing.ListModel;



/**
 *
 * @author MARZOOK
 */
public class client extends javax.swing.JFrame {

    /** Creates new form client */
    public client() {
        initComponents();
        
        
        try
        {
           sndSocket= new DatagramSocket();
        
        }
        catch(Exception e)
        {};
        
        listModel=new DefaultListModel();
        jList1.setModel(listModel);
    }

    client(Socket socket) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        connectbtn = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtnickname = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        publicbtn = new javax.swing.JButton();
        txtpublic = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtapublic = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtaprivate = new javax.swing.JTextArea();
        txtprivate = new javax.swing.JTextField();
        privatebtn = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        connectbtn.setText("connect");
        connectbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectbtnActionPerformed(evt);
            }
        });

        jLabel1.setText("Nickname");

        publicbtn.setText("send");
        publicbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                publicbtnActionPerformed(evt);
            }
        });

        txtapublic.setColumns(20);
        txtapublic.setRows(5);
        jScrollPane1.setViewportView(txtapublic);

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18));
        jLabel2.setText("   Users");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24));
        jLabel3.setText("Public Chat");

        jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 24));
        jLabel4.setText("Private Chat");

        txtaprivate.setColumns(20);
        txtaprivate.setRows(5);
        jScrollPane3.setViewportView(txtaprivate);

        privatebtn.setText("send");
        privatebtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                privatebtnActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jList1);

        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()
                .addComponent(connectbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(305, 305, 305)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(txtnickname, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(188, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 847, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtprivate, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(privatebtn, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(68, 68, 68)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(50, 50, 50)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtpublic, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(publicbtn))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(151, 151, 151))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connectbtn)
                    .addComponent(txtnickname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtpublic, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(publicbtn))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtprivate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(privatebtn))
                                .addGap(6, 6, 6))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(jLabel2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

private void publicbtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
// TODO add your handling code here:
    
   
      BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
      
      /* [STUDENTS - replace hostname with your machine's name or ip address ] */

      byte[] sendData = new byte[1024];
      

      /* Input sentence interactively from the user*/ 
      String sentence = listModel.firstElement() +":"+txtpublic.getText();
      /* Send the sentence to the server via UDP*/
      sendData = sentence.getBytes();
       
         try
         {
          
               
          InetAddress IPAddress =InetAddress.getByName("localhost");

          DatagramPacket sendPacket =new DatagramPacket(sendData, sentence.length(),IPAddress, 9988);
          sndSocket.send(sendPacket);
          
          }catch(Exception e) {}
         
          Thread thr = new Thread() {
            public void run() {
            while(true){
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket =new DatagramPacket(receiveData,receiveData.length);
                try{
                sndSocket.receive(receivePacket);
                }catch(Exception e) {}
                String modifiedSentence =new String(receivePacket.getData(), 0, receivePacket.getLength());
                txtapublic.append(modifiedSentence+"\n");
            }//  while
            
        }//run
        
        
       };  //thread       
        //publicbtn.setEnabled(false);
        thr.start(); 

      
      /* Receive response from server via UDP*/
      
      /* Print out modified user's sentence */

     /*sentence = txtmsg.getText();
      sendPacket.setData(sentence.getBytes());
      sndSocket.send(sendPacket);*/
      /* close the UDP socket */
     
      
}                                         

private void connectbtnActionPerformed(java.awt.event.ActionEvent evt) {                                           

    
    BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
    
      // [STUDENTS - replace hostname with your machine's name or ip address ] 

      byte[] sendData = new byte[1024];
      

      /* Input sentence interactively from the user*/
     
           String a = txtnickname.getText();
           // Send the sentence to the server via UDP
         sendData = a.getBytes();
       
        try
         {
          
               
          InetAddress IPAddress =InetAddress.getByName("localhost");

          DatagramPacket sendPacket =new DatagramPacket(sendData, a.length(),IPAddress, 9988);
          sndSocket.send(sendPacket);
          
          }catch(Exception e) {}
        
    
    
           Thread thr = new Thread() {
            public void run() {
            while(true){
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket =new DatagramPacket(receiveData,receiveData.length);
                try{
                sndSocket.receive(receivePacket);
                }catch(Exception e) {}
                String b =new String(receivePacket.getData(), 0, receivePacket.getLength());
                 listModel.addElement(b);
                 txtnickname.setText("\n");    
                 }//  while
            
         }//run
        
        
       };  //thread       
        //connectbtn.setEnabled(false);
        thr.start(); 

}                                          

private void privatebtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
// TODO add your handling code here:
     
    BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
      
      /* [STUDENTS - replace hostname with your machine's name or ip address ] */

      byte[] sendData = new byte[1024];
      
         
          
      /* Input sentence interactively from the user*/ 
            String x =listModel.firstElement()+" : "+txtprivate.getText();
      /* Send the sentence to the server via UDP*/
            sendData = x.getBytes();
       
          try
         {
               
          InetAddress IPAddress =InetAddress.getByName("localhost");

          DatagramPacket sendPacket =new DatagramPacket(sendData, x.length(),IPAddress, 9988);
          sndSocket.send(sendPacket);
          
          }catch(Exception e) {}
    
           
           
           
           Thread thr = new Thread() {
            public void run() {
             while(true){
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket =new DatagramPacket(receiveData,receiveData.length);
                try{
                sndSocket.receive(receivePacket);
                }catch(Exception e) {}
                String y =new String(receivePacket.getData(), 0, receivePacket.getLength());
                txtaprivate.append(y+"\n");
         }//  while
            
        }//run
        
        
      };  //thread       
        //privatebtn.setEnabled(false);
        thr.start(); 
         
        
    
    
    
}                                          

    /**
     * @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(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new client().setVisible(true);
            }
        });
    }
    
    
  
    
    
    DatagramSocket sndSocket;
    private javax.swing.DefaultListModel  listModel;
    // Variables declaration - do not modify                     
    private javax.swing.JButton connectbtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton privatebtn;
    private javax.swing.JButton publicbtn;
    private javax.swing.JTextArea txtaprivate;
    private javax.swing.JTextArea txtapublic;
    private javax.swing.JTextField txtnickname;
    private javax.swing.JTextField txtprivate;
    private javax.swing.JTextField txtpublic;
    // End of variables declaration                   

    
}
