import java.applet.Applet;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class Client2 extends Applet implements ActionListener
{

    Label label;
	TextField inputField;
	TextArea outputArea;
	Scrollbar redSlider;
    java.awt.List userList;

    //PrintWriter out;
    DataOutputStream out;

    Socket inSocket;
    Socket outSocket;
    Button stopButton;
    boolean flag=false;

    public class Listen extends Thread {

	//	ObjectInput in;
		BufferedReader/*DataInputStream*/ in;

		public void updateUsers(java.util.ArrayList list){
			  	userList.removeAll();
			  	Iterator e=list.iterator();
			  	while(e.hasNext())
					userList.add((String)e.next());

	    }
		public Listen() {
			System.out.println("Listen construction ");
			try {
				//in = new ObjectInputStream(inSocket.getInputStream());
				in = new BufferedReader(new InputStreamReader(new DataInputStream(
						inSocket.getInputStream())));
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("after initializing 'in'");
		}
		public void run() {
			//byte []/*String /*Object*/ o=new byte[10];
			String o;
			while (!flag) {
				try {
					o=in.readLine();
					/*if ((Class.forName("ArrayList")).isInstance(o))
						updateUsers((java.util.ArrayList)o);
					else */outputArea.append(o+"\n");

				} catch (Exception e) {
					e.printStackTrace();
				}
	    	}
		}
	   /* } catch(Exception e) {
	    } finally {
	      // Always close it:
	      try {
	        socket.close();
	      } catch(IOException e) {}
	     // threadcount--; // Ending this thread
	    }*/


/*				updateMessages(str);
			}
		}*/
	}

	/*public class Send extends Thread implements ActionListener {
		OutputStream out;
		public Send(Socket soc) {
			out = soc.getOutputStream();
		}
		public void run() {
			while (1==1) {
			}
		}
	}*/

    public void updateMessages(String msg) {

	 outputArea.append(msg+"\n");
	}

    public void init() {
        //-------------------------------------------------
        // create label
        label = new Label(" Enter your name:");
        label.setBackground(Color.lightGray);
        label.setForeground(Color.black);

        // create input field
        inputField = new TextField();
        inputField.addActionListener(this);
        inputField.setBackground(Color.white);

        // create panel for label and field and add them to it.
        Panel fieldPanel = new Panel();
        fieldPanel.setLayout(new BorderLayout());
        fieldPanel.add("West", label);
        fieldPanel.add("Center", inputField);
		//----------------------------------------
        stopButton=new Button("stop");
       // fieldPanel.add(/*"Bottom",*/ stopButton);
		//----------------------------------------
        // create the output area
        outputArea = new TextArea("");
        outputArea.setEditable(false);

        // create the panel for the field panel and output area
        // and add them to it.
        Panel appletPanel = new Panel();
        appletPanel.setLayout(new BorderLayout());
        appletPanel.add("North", fieldPanel);
        appletPanel.add("Center", outputArea);

        // create the user list.
        userList = new java.awt.List();
		redSlider=new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 255);
        add(redSlider);
        // add the applet panel and userlist to the applet
        this.setLayout(new BorderLayout());
        this.add("East", userList);
        this.add("Center", appletPanel);

        // set applet colors.
        setBackground(Color.lightGray);
        setForeground(Color.black);

        // show the components
        fieldPanel.setVisible(true);
        appletPanel.setVisible(true);
        setVisible(true);


      	try {
	 	 	// Create a socket
	 	 	System.out.println("before new inSocket ");
		  	inSocket = new Socket(InetAddress.getByName(getCodeBase().getHost())/*"ce.sharif.ac.ir"*//*getLocalHost()*/, NMultiJabberServer.OUT_PORT);
		  	System.out.println("after new inSocket ");
		  	try {
				Thread.sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("before new outSocket ");
		  	outSocket = new Socket(InetAddress.getByName(getCodeBase().getHost()/*"ce.sharif.ac.ir"*/)/*getLocalHost()*/, NMultiJabberServer.IN_PORT);
		  	System.out.println("after new outSocket ");
			/*out = new PrintWriter(
				 	 new BufferedWriter(
						new OutputStreamWriter(
			  				outSocket.getOutputStream())), true);*/
			out = new DataOutputStream(outSocket.getOutputStream());
	  		out.writeBytes/*println*/("login Client \n");

			Listen listen=new Listen();
			System.out.println("after new Listen");
			listen.start();
			System.out.println("after start Listen");

		/*s.close();

		// print out what we just received
		if (outputArea == null)
		            return;
		outputArea.append(str + "\n");
		outputArea.append(d + "\n");*/

   	   } catch (Exception e) {
   	      System.out.println(e.getMessage());
		  System.exit(1);
   	   }
	}

    public void actionPerformed(ActionEvent event){

   		if (event.getSource().equals(stopButton)) {
			try {
				out.writeBytes/*println*/("Logout Client \n");
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag=true;
		} else {
			String msg = inputField.getText();
	        if (msg.length() == 0)
	                   return;


	        try {
	   			out.writeBytes/*println*/("Client says: " + msg+"\n");
			} catch (Exception e) {
				e.printStackTrace();
			}

	        inputField.setText("");

	        return;
	   }
   }
}


