package pl.helion.j2mepp.serwerczata;

import java.io.*;
import java.net.*;

public class Watek extends Thread
{
 public Watek(Socket _gniazdo, MenadzerGniazdek _m)
 {
  try
  {
   gniazdo = _gniazdo;
   m = _m;
   in = new BufferedReader(new InputStreamReader(gniazdo.getInputStream()));
   out = new PrintStream(gniazdo.getOutputStream(),true);
  } 
  catch (Exception e) {}
 }
 public Socket getGniazdo()
 {
  return gniazdo;
 }
 public void wyslij(String tekst)
 {
  out.println(tekst); 
 }
 public void run()
 {
  String s = "";
  String[] tablica;
  try
  {
   while (true)
   {
    s = in.readLine();
    tablica = s.split(ZNAK);
    if (tablica[0].equals("hello"))
    {
     if (m.sprawdzLogin(tablica[1]))
     {
      this.wyslij("loginok");
      this.setLogin(tablica[1]);
      m.wyslijWiadomosc("msg"+ZNAK+"Przyszedl uzytkownik "+tablica[1]);
     } else this.wyslij("zlylogin");
    }
    if (tablica[0].equals("msg"))
    {
     if (tablica.length==4 && tablica[1].equals("priv"))
      m.wyslijWiadomosc(tablica[2],"msg"+ZNAK+this.getLogin()+"-PRIV->"+tablica[3]);
     else
      m.wyslijWiadomosc("msg"+ZNAK+this.getLogin()+">"+tablica[1]);
    }
   }
  }
  catch (Exception e)
  {
  }
  finally
  {
   this.zatrzymaj();
  }
 }
 public void zatrzymaj()
 {
  try
  {
   m.usunWatek(this);
   m.wyslijWiadomosc("msg"+ZNAK+"Uzytkownik "+this.getLogin()+" opuscil czat");
   gniazdo.shutdownInput();
   in.close();
   gniazdo.shutdownOutput();
   out.close();
   gniazdo.close();
  }
  catch (Exception e)
  {
  }
 }
 public void setLogin(String _login)
 {
  login = _login;
 }
 public String getLogin()
 {
  return login;
 }
 private Socket gniazdo;
 private String login;
 private MenadzerGniazdek m;
 private BufferedReader in;
 private PrintStream out;
 private final String ZNAK = "~";
}