/*
The code is available only to persons
currently affiliated with any of the following,
      o Universities and schools
      o Non-commercial research organizations
      o Registered not-for-profit organizations
      o Registered charities
For these people, the license is of the form of
the GNU Public License version 2.  The restrictions
must remain attached to this and any subsequently derived code.
All other people have no implicit right to use, read, or copy
this software unless granted by Mr. Deck
THIS SOFTWARE IS PROVIDED "AS IS" AND MR. DECK
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, HE
MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-
ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE
OF THE LICENSED SOFTWARE AND DOCUMENTATION WILL NOT
INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR
*/

import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.Hashtable;
import java.util.Enumeration;

public class saveDlg extends Frame implements Runnable {
TextField  tf = null; 
icontext   it = null;
Choice     ch = null;
Thread      t = null;

    public saveDlg(icontext i){
	super("Save");
        int hlfWid=150,hlfHt=140;
        int width=hlfWid<<1,height=hlfHt<<1;

        setLayout(null);
        setFont(env.font);
        setBackground(Color.white);
        setForeground(Color.black);

        asciiBut saveBut;
	saveBut = new asciiBut("OKAY",i);
        saveBut.reshape(hlfWid+10,199,60,30);
        add(saveBut);   

        asciiBut cancelBut;
	cancelBut = new asciiBut("CANCEL",i);
        cancelBut.reshape(hlfWid-73,199,73,30);
        add(cancelBut);   

	if(env.name.equals("")){
           tf = new TextField();
           tf.reshape(70,100,150,35);
           add(tf);
	   label slbl = new label(env.saveLbl);
	   slbl.reshape(0,70,width,25);
	   add(slbl);
	}else{
	   label lbl = new label(env.name);
	   lbl.reshape(70,100,150,35);
	   add(lbl);
	   label dlbl = new label(env.deriveLbl);
	   dlbl.reshape(0,70,width,25);
	   add(dlbl);
	}

        ch = new Choice();
	ch.addItem("art");
	ch.addItem("abstract");
	ch.addItem("commentary");
	ch.addItem("comic");
	ch.addItem("clever");
	ch.addItem("dense");
	ch.addItem("dialogue");
	ch.addItem("entertainment");
	ch.addItem("figurative");
	ch.addItem("hostile");
	ch.addItem("ideograms");
	ch.addItem("kid_stuff");
	ch.addItem("landscape");
	ch.addItem("narrative");
	ch.addItem("none");
	ch.addItem("nudes");
	ch.addItem("pattern");
	ch.addItem("philosophy");
	ch.addItem("poetry");
	ch.addItem("portraits");
	ch.addItem("stories");
	ch.addItem("trash");
	ch.addItem("visionary");
        ch.reshape(70,140,70,35);
	ch.select("none");
        add(ch);


	pack();
	reshape(getToolkit().getScreenSize().width/2-hlfWid,
	        getToolkit().getScreenSize().height/2-hlfHt,
		width,height);	
	show();   
	it = i;
    }	

    public boolean handleEvent(Event e){
        if(e.id == Event.KEY_PRESS){
            if(e.key == 10){
                this.hide();
	        it.da.repaint();
		return sendIt();
	    }
        }
        else if(e.id == Event.MOUSE_DOWN){
                //if(e.target instanceof Canvas){
                      if(e.target instanceof asciiBut){
                      	 this.hide();
		         it.da.repaint();
			 if(((asciiBut)e.target).getLabel()
				.equals("CANCEL"))
			  		this.dispose();
                         else return sendIt();
		      }
                //}
        }
        else if(e.id == Event.WINDOW_DESTROY){
                this.hide();
	        it.da.repaint();
		this.dispose();
	}
        return super.handleEvent(e);
    }               

    public boolean sendIt(){
	start();
        return true;
    }  

    public void start(){
	t = new Thread(this);
        t.setPriority(1);	
        t.start();
    }

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

    public void run(){
	String name;
        if(env.name.equals("")){
           name = tf.getText();
	   if(name!=null)
            name = name.trim().replace(' ','_')
	                      .replace('&','_')
	                      .replace(';','_')
                              .replace('*','x')
	                      .replace('$','S')
	                      .replace('\'','_')
	                      .replace('!','_');
	   else stop();
        }else{
           name = env.name;
        }
	Hashtable hash = new Hashtable();
	for(int i=0;i<50;i++){
	 for(int j=0;j<50;j++){
	    if(!hash.contains(it.ta.text[j][i])){
		Color c = (Color)it.ctab.get(it.ta.text[j][i]);
	        hash.put(it.ta.text[j][i],
		new String("\""+it.ta.text[j][i].toString()+" c #"+it.getHex(c.getRed(),c.getGreen(),c.getBlue())+"\",\n"));
	    }
	 }
	}
       String header = new String("/* XPM */\nstatic char *"
                       + name + "[]={\n/*<!--*/\n\"50 50 " 
                       + hash.size() + " 1\",\n");
       byte   HEADER[] = new byte[header.length()];
       String pre = new String(
        "/*--><pre><a name=i></a><form method=post action=/icontext/cgi/next.php3><input type=image src=/icontext/cgi/xpmtogif.cgi?"
        +name+".html.gz> <font size=+4 face=\"courier new,courier\"><b>"+name+"</b></font><img src=/icons/b.gif width=2000 height=1>*/\n");
       String end = new String("};\n/*<input name=self value="+name+" type=hidden><input name=link value=default type=hidden><input name=cat value="+ch.getSelectedItem()+" type=hidden></form>*/\n");
       byte[] endbytes = new byte[end.length()];
       end.getBytes(0,end.length(),endbytes,0);
       
       byte[] prebytes = new byte[pre.length()];
       pre.getBytes(0,pre.length(),prebytes,0);
       String len = (new Integer(pre.length()+header.length()+
		         end.length()+2700+hash.size()*15)).toString();
       String post=new String("POST /java/icontext/cgi/save.cgi?"
              +name+ " HTTP/1.0\n" + "Content-Length: "+len+"\n"
              +"User-Agent: " + System.getProperty("java.vendor")
              + " " + System.getProperty("os.name")+"\n\n");  
	byte[] POST = new byte[post.length()];
  	String line         = null;
	Socket sock         = null;
  	DataInputStream is  = null;
	OutputStream os;
	header.getBytes(0,header.length(),HEADER,0);
	post.getBytes(0,post.length(),POST,0);
	try{
		sock = new Socket(env.host, 80); 
		os = sock.getOutputStream();
	        os.write(POST);
		os.write(HEADER);
		byte[] entry = new byte[15];
		Enumeration e = hash.keys();
		String s;
		while(e.hasMoreElements()){
		   s = (String)hash.get(e.nextElement());
		   s.getBytes(0,15,entry,0);
		   os.write(entry);
		}
		os.write(prebytes);
		for(int i=0;i<50;i++){
		 sock.getOutputStream().write('"');
		 for(int j=0;j<50;j++){
			os.write(it.ta.text[j][i].charValue());
		 }
		 os.write('"');
		 os.write(',');
		 os.write(10);
		}
		os.write(endbytes);
		System.out.println(len);
		is = new DataInputStream(
		  new BufferedInputStream(sock.getInputStream()));
		while((line= is.readLine()).length()>1) ;
		if((line = is.readLine()) !=null){
			it.usrLab.setText(line);
		}
		System.out.println("done");
	    }
	    catch(EOFException io){
	    }
	    catch(IOException ex){
	    }
	    finally{
	       t=null;
		try{
		  if(sock!=null) sock.close();
		  sock=null;
		}catch(IOException e){}
                this.dispose();
	    }
        } // endrun
}

