package pl.helion.j2mepp.klientczata;

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class KlientCzataMIDlet extends MIDlet implements CommandListener
{
	public KlientCzataMIDlet()
	 {
	  ekran = Display.getDisplay(this);
	  formadane = new Form("Polacz z serwerem");
	  poleHost = new TextField("Wprowadz host:","127.0.0.1",100,TextField.ANY);
	  poleLogin = new TextField("Wprowadz login:","",30,TextField.ANY);
	  formadane.append(poleLogin);
	  formadane.append(poleHost);
	  Command wejdz = new Command("Wejdz",Command.OK,0);
	  formadane.addCommand(wejdz);
	  formaglowna = new Form("Czat");
	  poleInput = new TextField("Tekst:","",100,TextField.ANY);
	  formaglowna.append(poleInput);
	  Command wyslij = new Command("Wyslij",Command.OK,0);
	  Command koniec = new Command("Koniec",Command.EXIT,0);
	  formaglowna.addCommand(wyslij);
	  formaglowna.addCommand(koniec);
	  etykiety = new StringItem[5];
	  for (int i=0;i<5;i++)
	  {
	   etykiety[i] = new StringItem("","");
	   formaglowna.append(etykiety[i]);
	  }
	  formadane.setCommandListener(this);
	  formaglowna.setCommandListener(this);
	  ekran.setCurrent(formadane);
	 }
	 public void startApp()
	 {
	 }
	 public void pauseApp()
	 {
	 }
	 public void destroyApp(boolean unconditional)
	 {
	  if (watek!=null)
	   watek.zatrzymajWatek();
	 }
	 public void commandAction(Command c, Displayable s)
	 {
	  if (s == formadane)
	  {
	   if (c.getCommandType() == Command.OK)
	   {
	    if (!poleHost.getString().equals("") && !poleLogin.getString().equals(""))
	    {
	     watek = new WatekKlienta(poleHost.getString(), poleLogin.getString(),this);
	     watek.start();
	    }
	   }
	   if (c.getCommandType() == Command.EXIT)
	   {
	    this.notifyDestroyed();
	   }
	  }
	  if (s == formaglowna)
	  {
	   if (c.getCommandType() == Command.OK)
	   {
	    if (!poleInput.getString().equals(""))
	    {
	     Thread send = new Thread(new Runnable(){
	      public void run()
	      {
	       if (watek!=null)
	       watek.wyslij("msg"+ZNAK+poleInput.getString());
	       poleInput.setString("");
	      }
	     });
	     send.start();
	    }
	   }
	   if (c.getCommandType() == Command.EXIT)
	   {
	    destroyApp(true);
	   }
	  }
	 }
	 public void pokazKomunikat(String tekst)
	 {
	  a = new Alert(tekst);
	  a.setTimeout(3000);
	  ekran.setCurrent(a);
	 }
	 public void zaloguj(boolean wartosc)
	 {
	  if (wartosc)
	   ekran.setCurrent(formaglowna);
	  else
	   this.pokazKomunikat("Uzytkownik o podanym loginie istnieje!");
	 }
	 public void dodajTekst(String tekst)
	 {
	  for (int i=0;i<4;i++)
	  {
	   etykiety[i].setText(etykiety[i+1].getText());
	  }
	  etykiety[4].setText(tekst+"\r\n");
	 }
	 private WatekKlienta watek;
	 private StringItem[] etykiety;
	 private Form formadane;
	 private Form formaglowna;
	 private Display ekran;
	 private Alert a;
	 private TextField poleLogin;
	 private TextField poleInput;
	 private TextField poleHost;
	 private final String ZNAK = "~";
}
