/* Copyright Andy C. Deck 1999 All rights reserved. */    
import java.awt.*;
import java.io.*;
import java.net.*;

public class openStudio extends java.applet.Applet implements Runnable{
Thread t;
drawPanel dp;
cntlPanel cntl;
Image     img;
label usrLab = new label(Env.welcome);

public static int pr[] = {
 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11, 11, 12, 
 12, 13, 13, 14, 14, 15, 16, 17, 18, 19 }; 

   public static void main(String args[]){
        boolean useTablet=false;
        for(int i=0;i<args.length;i++){
                if(args[i].indexOf("-t")>=0)  useTablet = true;
        }
        openStudio ops =  new openStudio();
        Frame      f1 =  new Frame("openStudio");
        Dimension   d =  ops.getToolkit().getScreenSize();
        f1.add("Center",ops);
        f1.reshape(-5,-25,d.width+10,d.height+30);
        f1.show();
        if(useTablet){
               new tablet(ops);
        }
        ops.init("artcontext.com");
        ops.start();
        /*Runtime rt    = Runtime.getRuntime ();
        rt.gc ();
        System.out.println ("Total Memory Available = " + (long)rt.freeMemory());
        System.out.println ("Free Memory Available  = " + (long)rt.totalMemory());*/
   }

   public void init(){
	 String param = getParameter("HOST"); 
	 if(param != null) Env.host = param;
	 String portStr = getParameter("PORT"); 
	 if(portStr != null) Env.port = Integer.parseInt(portStr);
         if(param != null) init(param);
         else init("artcontext.com");
   }    

   public void init(String host){
     Env.host = host;
     Dimension d = size();
         if(img==null){
	     img = createImage(d.width-137,d.height);
	     dp = new drawPanel(this,img);
	     dp.reshape(136,0,d.width-136,d.height);
	     add(dp);	
	     add(cntl = new cntlPanel(this));
	     cntl.reshape(0,0,136,d.height); 
	 }
	 //dp.play(""); 
   }

   public openStudio(){
	setBackground(Color.darkGray);
	setLayout(null);
	setFont(Env.font);
   }

   public void start(){
	t = new Thread(this);
	t.setPriority(Thread.MIN_PRIORITY+2);
	t.start();
   }
	
   public void stop(){
	closeConnection(Env.welcome);
	if(t!=null) t.stop();
	t = null;
   }
	
   private void closeConnection(String msg){
	 if(dp.con != null){
               dp.con.close();
	       dp.con = null;
   	 }
	 usrLab.setText(msg);
   }

   public void destroy(){
	dp.bufImg.flush();
	if(dp.con != null)      dp.con.error = true;
	if(cntl.cpick.pal != null) cntl.cpick.pal.dispose();
   }

   public String getAppletInfo() { return "OpenStudio applet (C) Andy C. Deck"; } 

   public void run()
   {
    byte[] buf=null;
    dp.con = new connection(Env.host,Env.port,usrLab);
    while (t!=null && !dp.con.error)
    {
        try{ 
	    if(dp.con!=null){
		buf = null;
		buf = dp.con.receive(); 
	    }
	}
	catch(NullPointerException nex){
	    System.out.println("openStudio(1)"+nex);
	    nex.printStackTrace();
	    continue;
	}
	catch(IOException e){
	     System.out.println("openStudio(2)"+e);
	     dp.con.error = true;
             usrLab.setText(Env.disconnected);
	     break;
	}
	if( buf !=null ){
	    switch(buf[0]){
		case Env.UPDATE:
		  	usrLab.setText(buf[1]+" "+ (buf[1]>1?Env.users:Env.user));
			break;
		case Env.TEXT:
			System.out.println("foo");
			if(cntl.chat!=null)
                       cntl.chat.addText(new String(buf,0,2,buf.length-2));
			else System.out.println("cntl.chat = null");
			break;
		/*case Env.REJECTION:
			 usrLab.setText(Env.overmax);
			break;*/
		default:
		 	//while(dp.penDown) t.yield();
            		handleStroke(buf,buf.length);
	    }
	}
	else System.out.println("buf[0]="+buf[0]);    
     }
     closeConnection(Env.tryreload);
   }

  Color[] col = new Color[Env.MAX_USERS];   
  int type[] = {0,0,0,0,0,0,0,0,0,0 };
  Item d = new Item();
  Rectangle rect=null;

   public void handleStroke(byte[] buf,int len){
	if(buf[0]>Env.MAX_TOOL){
		System.out.println(buf[0]+" too big tool");
		 return;
	}
        d.type = (buf[0]>=0&&buf[0]<Env.MAX_TOOL?buf[0]:0);     // type
	d.id = ((buf[1]>=0&&buf[1]<Env.MAX_USERS)?buf[1]:8);
	d.press = 0; 
	d.x=(short) (buf[4]<0?(buf[3]<<8|buf[4]+255):(buf[3]<<8|buf[4]));
       	d.y=(short) (buf[6]<0?(buf[5]<<8|buf[6]+255):(buf[5]<<8|buf[6]));
        d.r    = buf[7];     // R color
        d.g    = buf[8];     // G color
        d.b    = buf[9];     // B color      
	if(d.type<Env.MAX_TOOL && d.type >= 0){
		 type[d.id] = d.type;
	         col[d.id]=new Color(d.r<0?d.r+255:d.r,d.g<0?d.g+255:d.g,d.b<0?d.b+255:d.b);
		 dp.g.setColor(col[d.id]);
		 (Env.strokes[d.type]).init(d);
		 try{
		if(buf[2]>=0){
		    d.press = buf[2];
	            for(int i = 10; i<len;i+=4){
		        rect = Env.strokes[type[d.id]].fill(dp.g,d);
		        d.x=(short)
				(buf[i+1]<0?(buf[i]<<8|buf[i+1]+255):(buf[i]<<8|buf[i+1]));
       		        d.y=(short)
				(buf[i+3]<0?(buf[i+2]<<8|buf[i+3]+255):(buf[i+2]<<8|buf[i+3]));
	   		dp.repaint(rect.x,rect.y,rect.width,rect.height);
		    } 
		}else{
	            for(int i = 10; i<len;i+=5){
		        rect = Env.strokes[type[d.id]].fill(dp.g,d);
		    	d.press = buf[i];
		        d.x=(short)
				(buf[i+2]<0?(buf[i+1]<<8|buf[i+2]+255):(buf[i+1]<<8|buf[i+2]));
       		        d.y=(short)
				(buf[i+4]<0?(buf[i+3]<<8|buf[i+4]+255):(buf[i+3]<<8|buf[i+4]));
	   		dp.repaint(rect.x,rect.y,rect.width,rect.height);
		    } 
		}
       		 try{ Thread.currentThread().sleep(len); } 
		 catch(InterruptedException ee){}
		}catch(Exception ee){
			ee.printStackTrace();
                }
	    }
	}
}
