import java.awt.*;
import java.applet.*;
import java.net.*;
import java.io.*;
import java.util.zip.*; 


public class glyphiti extends Applet implements Runnable{
String[]       pad = null;
String     baseURL = null;
Image          img = null;
Image          all = null;
Image        smImg = null;
Thread           t = null;
String         num = null;
byte[][]     icon  = null;
boolean   initMode = true;
int         curImg = 0;
int    WHITE;
int    BLACK;
int      YES;
int       NO;
int            ttl;
int       doUpdate;
glyphEdit       gc = null; 

    public void init(){
        curImg = 0;
        WHITE = 64;
        BLACK = 65;
        YES = -2;
        NO = -1;
        ttl = 255;
        doUpdate = NO;
        gc = null; 
        baseURL = "http://artcontext.org/act/01/glyphiti/";
        pad = new String[33];
        icon  = new byte[32][32];
	setBackground(Color.white);
	setLayout(null);
	all = getImage(getCodeBase(),"../docs/presentStateImg.php");
	img = createImage(512,512);
	pad[32] = "";
	for(int i=31;i>0;i--){
		pad[i] = pad[i+1]+"0";
	}
    }
	
    public void update(Graphics g){
	paint(g);
    }

    public void paint(Graphics g){
        if(img!=null){
	  if(doUpdate>NO){
	     Graphics ig= img.getGraphics();
	     ig.translate((curImg%16)<<5,(curImg/16)<<5);
	     ig.setColor(Color.white);
	     ig.fillRect(0,0,32,32);
	     ig.setColor(Color.black);
             for(int y=0;y<32;y++)
               for(int x=0;x<32;x++)
                     if(icon[y][x] == BLACK) ig.drawLine(x,y,x,y);
	     doUpdate = NO;
	  }
	  g.drawImage(img,0,0,null);
	}
    }

    public boolean mouseDown(Event e, int x, int y){
        int which = (x>>5) + ((y>>5)<<4); 
	if(which<0 || which>255) return true; 
	if(gc!=null) remove(gc);
	gc=new glyphEdit(which,this);   
	add(gc);
	ttl = 255;
	return true;
    }
    public void start(){
       t = new Thread(this);
       //t.setPriority(Thread.MIN_PRIORITY);
       t.start();
    }

    public void stop(){
      if(t!=null) t.stop();
      t = null;
    }                   

    public void run(){
	URLConnection urlcon = null;
        String  lastMod = "0";
	long sleepTicks = 5000;

	if(initMode){
	    Frame f = null;
            for(Object obj = this; (obj = ((Component) (obj)).getParent()) != null;)
	    {
               if(obj instanceof Frame)
               {
                  f = (Frame)obj;
                  break;
	       }
            }
            if(f!=null) f.setCursor(Frame.WAIT_CURSOR);
	    try{
                MediaTracker mt = new MediaTracker(this); 
                mt.addImage(all,0);
	        mt.waitForAll();
	        Graphics g = img.getGraphics();
	        if(g!=null){
	           g.drawImage(all,0,0,null);
	           g.dispose();
                }
	    }catch(Exception e){
	        if(img!=null){
			Graphics g = img.getGraphics();
	        	if(g!=null){
	           		g.drawString("Error loading base image.",235,250);
	           		g.dispose();
                	}
		}else System.out.println("Error loading img. img=null");
            }
            if(f!=null) f.setCursor(Frame.DEFAULT_CURSOR);
	    initMode=false;
	    repaint();
	}
        String str = "";
	while(t!=null && ttl>0){
            try{ 
		int y = 0;
                int X=0,Y=0;
        	URL url = new URL(getCodeBase(),"../docs/current.php?lm="+lastMod);
		urlcon = url.openConnection();
               	urlcon.setDoOutput(false);
               	urlcon.setUseCaches(false);
		urlcon.connect();
		DataInputStream din;
               	if(urlcon.getContentType().indexOf("text/plain")==0 ){
		     din = new DataInputStream(urlcon.getInputStream());
		}
		else{
			/*
               	     if(urlcon.getContentType().equals("text/html")){
		      din = new DataInputStream(urlcon.getInputStream());
		       while((str = din.readLine())!=null){
				System.out.println(str);
		      } 
                     }*/
		     din = new DataInputStream(new GZIPInputStream(urlcon.getInputStream()));
		     doUpdate = YES;
		}
		if(din!=null){
		   while((str = din.readLine())!=null){
			System.out.println(str);
			if(str.charAt(0)=='#'){
				curImg = Integer.parseInt(str.substring(2).trim());
				if(doUpdate==YES) doUpdate=curImg;
			}
			else if(str.charAt(0)=='@'){
				String curFileTimeStamp = str.substring(2).trim();
				if(Long.parseLong(curFileTimeStamp) > Long.parseLong(lastMod))
				      lastMod = curFileTimeStamp;
			}else if(str.length()>0){
				String pix = Long.toString(Long.parseLong(str.substring(0,str.length()-1),36),2)+	
						(String)(str.substring(str.length()-1).equals("W")?"0":"1");
				pix = pad[pix.length()] + pix;
				for(int x=0;x<32;x++){
                               		if(pix.charAt(x) == '0') icon[y][x] = (byte)WHITE;
                               		else                     icon[y][x] = (byte)BLACK;
				}
				y++;
			}
		 }//endwhile
		 if(din!=null) din.close();
		 if(doUpdate>NO){
		 	X = ((curImg%16)<<5); 
			Y = (curImg/16)<<5;
			repaint(X,Y,32,32);
		 }
		}//endif

	    }catch(NullPointerException npe){
		      	npe.printStackTrace();
	    }catch(Exception io){ 	
			io.printStackTrace(); 
	    }

 	    ttl--;
	    try{
	        if(t!=null) t.sleep(sleepTicks+=25); 
	    }catch(Exception ee){
		ee.printStackTrace();
            }
	}
    }
}
