import java.awt.*; 
import java.io.InputStreamReader;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class CC implements Runnable 
 {
  static double loopsleep=200;
  boolean deb=false;
  static boolean bong=true;
  double bongcount=0;
  String clid="new";
  String chatid="";
  int port=8728;
  boolean request=false,cable=false,conn=false;
  boolean dc=true,quite=true;
  boolean interpret=true;
  TA ta0,ta1,ta2,ta3;
  Socket soc;
  DataInputStream dis;
  BufferedReader br;
  InputStreamReader isr;
  Scanner scanner;
  Scanner scin;
  PrintStream os;
  Thread thr;
  static M parent;
  URL chatcodebase;
  Te te;
  boolean exframe;
  String name="chat";
  LF lfch;
  Bu chatlbu;
  LSpP lspp,lsppcc;
  String yhi="Your handle is:";
  boolean ncrflag=false;
  String lspppos;
  @SuppressWarnings("unchecked")
  public CC(String name,URL ccb,int port,LSpP lspp,String lspppos) 
   {
    this.name=name;
    chatcodebase=ccb; 
    this.port=port;
    this.lspp=lspp;
    this.lspppos=lspppos;
    te=parent.te;
    Te.CCh.put(name,this);
    ta0=parent.ta0;
    ta0.cc=this;
    ta1=parent.ta1;
    ta2=parent.ta2;
    ta3=parent.ta3;
    ta2.cc=this;
    ta3.cc=this;
    parent.cc=this;
    tta2(name+" hello from tta2");
    tta3(name+" hello from tta3");
    chatlbu=new Bu("chat"+name,parent.lp1,"chat",new String[] {"Checking for Chat"},0,false,new dP(-1000,-1000));
    chatlbu.cc=this;
    // tta("CC consturctor port:"+port+" ccb:"+ccb);
    //tta("CC:"+name+" LSpP:"+lspp.name+" lspppos:"+lspppos.name);
    //tta("CC:"+name);
   }
  public void mkguiprep()
   {
    mkgui();
    tta2("Type your message here");
    return;
   }
  public void mkgui()
   { 
    if(true) return;
   }
  /*
  public void layoutLSpP()
   {
    parent.lsppv.setDiv(.5);
    parent.lsppbh.setDiv(.5);
    parent.lsppblv.max();
    parent.newTeS("lspp"+name+".div - lsppbh.rs.y 100");
    schleep(300);
    parent.lsppbh.doLayout();
    schleep(300);
   }
  */
  public void init() { }
  public void start()
   {
    thr=new Thread(this,"main");
    thr.start();
   }
  void setlabel(String s,boolean b,long zzz)
   {
    chatlbu.setlabel(s,b);
    schleep(zzz);
   }
  public void setport(int port)
   {
    this.port=port;
    cable=false;
    request=false;
    conn=false;
   }
  public void run()
   {
    cable=false;
    request=true;
    conn=false;
    int t=0;
    while (t < 3)
     {
      if (!cable) 
       {
        testforcapability();
        if (!cable)  t++;
       }
      else if(!request)
       {
        // deb("CC.run  cable:"+cable+" request:"+request+" conn:"+conn+"  t:"+t+" capable but not connected");
        schleep(1000); 
        t++;
       }
      else if(! conn) testforconnection();
      else if(cable && request && conn) 
       {
        //  deb("cable request conn all true going to connected()");
        connected();
       }
      else
       {
        deb("deep mon");
        schleep(1000); 
       }
     }
    setlabel("Chat is not available",false,300);
   }
  void testforcapability()
   {
    //String s=te.fio.realload(chatcodebase,port+"chatstat.html",false,false);
    //deb("Chatcodebase:"+chatcodebase+" file:"+port+"chatstat.html:"+s+ " cable:"+parent.te.Svo(cable));
    //setlabel("Checking for Chat",false,500);
    //if(s.indexOf("false")>-1) setlabel("Chat is not available",false,30000);
    //else 
    //{
    //cable=true;
    //setlabel("Chat is available now",false,500);
    //setlabel("Join Chat",true,0);
    //}
    cable=true;
    //setlabel("Chat is available now",false,500);
    setlabel("Join Chat",true,0);
   }
  void bongoff()
   {
    bongcount=0;
    bong=false;
   }
  void connected()
   {
    deb("connected()");
    while (conn)
     {
      //  try
      //   {
      // deb(name+" while connected"); 
      if(true)
       {
        //  deb("dis.ready to readUTF()");
        //deb("br is ready to readLine()");
        // String s=br.readLine();
        //  String s=dis.readUTF();
        String s="";
        if (scin==null) 
         {
          tta("scin is null");
          return;
         }
        deb("scin ready");
        while(scin.hasNextLine())
         {
          s=scin.nextLine();
          recproc(s);
         }
        deb(name+".connected()  Post xxx() s:"+s+":");
       }
      else           deb("something not ready");
      //   }
      //    catch(IOException e){}
     } 
    disconnect();
   }
  void recproc(String s)
   {
    String cntrl="";
    String post="";
    String arg="";
    String sarg="";
    int pipeindex= s.indexOf("|");
    int colonindex=s.indexOf(":");
    deb ("recproc s:"+s+" pipeindex:"+pipeindex+" colonindex:"+colonindex);
    if(pipeindex>-1)
     {
      cntrl=s.substring(0,pipeindex);
      if(colonindex>-1)
       {
        arg=cntrl.substring(0,colonindex);
        sarg=cntrl.substring(1+colonindex);
        deb("arg:"+arg+": sarg:"+sarg+":");
        if(arg.equals("setchatid"))
         {
          if(chatid.equals("") )
           {
            chatid=sarg;
            tta("CC.recproc Chat ID:"+chatid);
           }
          else
           {
            tta("Attempt to reset chatid");
           }
         }
        else
         {
          tta("recproc  ready to handle cntrl:"+cntrl);
         }
       }
      else 
       {
        tta("recproc no colonindex no problem");
        String tes=s.substring(1+pipeindex);
        parent.newTeS(tes);
       }
     }
    else
     {
      tta("recproc no pipeindex");
     }
   }
  void sendo(String s)
  {
	  ctrlSendo(chatid+"|"+s);
  }

  void ctrlSendo(String text)
   {
   deb(name+".ctrlSendo text:"+text);
    os.println(text);
    os.flush();
   }
  void tta3ncr(String s) 
   {
    if(ta3 == null) return;
    ta3.append(s);
    ta3.carettoend();
    ncrflag=true;
   }
  void tta3(String s) 
   {
    if(ncrflag) tta3ncr("\n");
    tta3ncr(s+"\n");
    ncrflag=false;
   }
  void tta2(String s) 
   {
    if(ta2 == null) return;
    ta2.append(s+"\n");
    ta2.carettoend();
   }
  void tta1(String s) { ta1.append(s+"\n"); }
  void tta(String s) { ta0.append(s+"\n"); }
  void deb(String s) { if(deb) tta(s); }
  void testforconnection()
   {
    String s=connlib();
    if(conn) 
     {
      mkguiprep();
      chatlbu.setlabel("Exit Chat",true);
      ctrlSendo("settype:JavaClient|");
      schleep(100);
      ctrlSendo("reqchatid|");
     }
    else 
     {
      setlabel(s,false,3000);
      setlabel("Chat is unavailable",false,0);
     }
   }
  String connlib()
   {
    // tta("CC.connlib");
    try 
     {
      //   deb("connlib in first try");
      try 
       {
        //     deb("connlib in second try");
        if(chatcodebase != null)
         {
          String str =chatcodebase.getHost();
          //  deb("connlib :"+name+" soc=new Socket(\"192.168.0.56\",8728)");
          //soc=new Socket(chatcodebase.getHost(),port);
          soc=new Socket("192.168.0.56",8728);
          Scanner scanner=new Scanner(System.in);
          scin=new Scanner(soc.getInputStream());
          // dis=new DataInputStream(soc.getInputStream());
          //br=new BufferedReader(new InputStreamReader(System.in));
          //tta("CC.conlib socket and br crated");
          deb("CC.conlib socket and scin crated");
         }
        else
         {
          deb("connlib new Socket chatcodebase is nul this shouldn't workl");
          soc=new Socket("",port);
         }
        deb("connlib bottom of second try");
       }
      catch(UnknownHostException ee) 
       {
        deb("connlib catch first try Unknown Host Exception:"+ee.toString());
        return "connlib catch first try Unknown Host Exception:"+ee.toString(); 
       }
     }
    catch(IOException e) 
     {
      cable=false;
      deb( "CC."+name+" IOExceptiion e:"+e.toString());
      return "CC."+name+" IOExceptiion e:"+e.toString();
     }
    // try 
    // { 
    //now dis=new DataInputStream(new BufferedInputStream(soc.getInputStream()));
    deb(name+".connlib br created");
    //	}
    //catch(IOException e) { return "Problem with DataInputStream creation"; }
    try { os=new PrintStream (new BufferedOutputStream(soc.getOutputStream(),1024), false); }
    catch(IOException e) { return "Problem with PrintStream creation"; }
    conn=true;
    return "Chat is Connected";
   }
  void disconnect(String s)
   {
    sendo(s);
    disconnect();
   }
  void disconnect() 
   {
    whoa(); 
    ta3.dofin();
    ta2.dofin();
    lsppcc.dofin();
    if(lspp.name.equals("lsppbh"))
     {
      parent.lsppbh.max();
      parent.lsppv.ret();
      schleep(600);
      parent.lsppblv.max();
     }
    setlabel("Chat is disconnected",false,2000);
   }
  public void whoa()
   {
    String error="";
    if (os !=null) sendo ("loging off");
    if (os !=null) os.close();
    try { if (dis !=null) dis.close(); }
    catch(IOException e) { error="Error closing DataInputStream"; }
    try { if (soc !=null) soc.close(); }
    catch(IOException e) { error="Error closing Socket"; }
    if(error.equals("")) tta2("Succesfully logged off");
    else tta3(error);
    conn=false;
    cable=false; 
    request=false;
   }
  public void ed()
   {
    tta1(name+".interpret "+Te.Svo(interpret));
    tta1(name+".dc "+Te.Svo(dc));
    tta1(name+".chatcodebase "+"\""+chatcodebase+"\"");
    tta1(name+".port "+Te.Svo(port));
    tta1(name+".loopsleep "+Te.Svo(loopsleep));
    tta1(name+".bong "+Te.Svo(bong));
    tta1(name+".deb "+Te.Svo(deb));
   }
  void mp()
   {
    deb("mp  label:"+chatlbu.label);
    if(chatlbu.label.equals("Exit Chat")) chatlbu.swender();
    else if(chatlbu.label.equals("Join Chat")) chatlbu.swender();
   }
  void mr()
   {
    deb("mr  label:"+chatlbu.label);
    if(chatlbu.label.equals("Exit Chat"))
     {
      conn=false;
      chatlbu.swender();
     }
    else if(chatlbu.label.equals("Join Chat"))
     {
      if(cable) request=true;
      chatlbu.swender();
     }
   }
  void schleep(long zzz)
   {
    try { thr.sleep(zzz); }
    catch(InterruptedException e) { }
   }
 }
