// Copyright Andy Deck 2003, GNU Public License 2
// With the notable provision that any commercial use
// must be approved by the copyright holder.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Date;

public class saver extends Panel implements Runnable {
asciiJam  aj = null;
Thread t = null;
String fmt = "html";
String name = "";

    public void show(){
        setFont(env.dialogFont);
        super.show();
    }
    public saver(asciiJam ajam){
        this.aj = ajam;
        this.setLayout(null);
        this.resize(123,200);
        this.setBackground(Color.black);
        Panel inner = new Panel();
        inner.setLayout(new GridLayout(7,1,0,4));
        inner.resize(size().width-2,size().height-2);
        inner.move(1,1);
        inner.setBackground(Color.lightGray);
        inner.add(new Label(" Save Prefs"));
        CheckboxGroup group1 = new CheckboxGroup();
        inner.add(new Checkbox("HTML",group1,true));
        inner.add(new Checkbox("PDF",group1,false));
        inner.add(new Checkbox("ASCII",group1,false));
        inner.add(new Label(" Name of file:"));
        Panel p = new Panel();
        p.setLayout(new FlowLayout(1,0,0));
        //p.setLayout(new GridLayout(2,1,0,4));
        TextField tf = new TextField(10);
        tf.setText("");
        p.setFont(new Font("Helvetica",Font.PLAIN,10));
        p.add(tf);
        inner.add(p);
        p = new Panel();
        p.setFont(new Font("Helvetica",Font.PLAIN,8));
        p.setLayout(new FlowLayout(1,0,0));
        p.add(new Button("Save"));
        inner.add(p);
        add(inner);
 }

 public void saveNow(){
	start();
 }

 public void start(){
 	t = new Thread(this);
	t.start();
 }
 public void stop(){
     if(t!=null) t.stop();
	 t=null;
 }

    public void run(){
	int ch = 0;
		int colorOffset = (env.width>>3)*(env.height>>4);	
        String body = "";
        String colors = "";
		int rowmax = (env.height/16)-1;
		int colmax = (env.width/8);
	for(int row=rowmax;row>=0;row--){
		 int rowOffset = row<<7;
	 	 for(int col=0;col<colmax;col++){
			body = body.concat( ""+(char)+(aj.ta.text[col+rowOffset])) ;
			int off = col+rowOffset+colorOffset;
			int hiByte = aj.ta.text[off]>>4; 
			int loByte = aj.ta.text[off]%16;
			colors = colors.concat( dec2hex(hiByte)+""+dec2hex(loByte) );
			//if((char)aj.ta.text[col+rowOffset]!=' ') System.out.println("c="+(char)aj.ta.text[col+rowOffset]+" hi="+hiByte+" lo="+loByte+" "+  dec2hex(hiByte)+""+dec2hex(loByte));
		 }
		 body = body.concat("\n");
		 colors = colors.concat("\n");
	}
		body = body + colors;
       System.out.println(body);
       byte   BODY[] = new byte[body.length()];
       String len = (new Integer( BODY.length).toString());
       String post=new 
	   	String("POST "+env.basedir+"docs/saver.php?format="+fmt+"&name="+name+" HTTP/1.1\n" 
		+ "Content-length: "+len+"\n"
		+ "Host: "+env.host+"\n"
		+ "Connection: close\n"
		+ "Content-type: text/plain\r\n\r\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;
	body.getBytes(0,body.length(),BODY,0);
	post.getBytes(0,post.length(),POST,0);
	String fname="";
	try{
		sock = new Socket(env.host, 80); 
		os = sock.getOutputStream();
	    os.write(POST);
		os.write(BODY);
		is = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
		while((line= is.readLine()).length()>1) ;
		while((line = is.readLine()) !=null){
			fname = line;
			System.out.println(fname);
		}
		//System.out.println(len+" byte file: "+line);
	    }
	    catch(EOFException io){
		io.printStackTrace();
	    }
	    catch(IOException ex){
		ex.printStackTrace();
	    }
	    finally{
		try{
		  if(sock!=null) sock.close();
		  sock=null;
		}catch(IOException e){
		   e.printStackTrace();
		}
                //this.dispose();
	    }
        try{
			Date d = new Date();
			int year = d.getYear();
			if(year<150) year+=1900;
			if(fname != "")
            aj.getAppletContext().showDocument(
			new URL(env.viewFileURL+"?format="+fmt+"&name="+fname+"&year="+year),"_blank");
        }catch(Exception ex){}
    } // endrun

   public String dec2hex(int i){
        if(i<10)
          return Integer.toString(i);
        else{
          byte b[] = {(byte)(i+55)};
          return new String(b,0);
        }
   }

   public static String safeChars(String source) {
        int i, len = source.length();
        StringBuffer dest = new StringBuffer(len);

        for (i = 0; i < len; i++) {
			char c = source.charAt(i);
            if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='_'||c=='.')
                 dest.append(c);
            else dest.append('x');
        }
        return dest.toString();
   }

     public boolean handleEvent(Event e){
     if(e.target instanceof Button){
        if(e.id==1001)
			saveNow();			
     }else if(e.target instanceof TextField){
        if(e.id==402){
			((TextField)e.target).handleEvent(e);
            String s = ((TextField)e.target).getText();
            if(s!=null&&s.length()<14){  // don't add past 14 characters
                name = safeChars( s.trim().replace('^','r').replace('%','X').replace('?','7').replace(' ','_').replace('&','8').replace(';','_').replace('*','x').replace('$','S').replace('!','1').replace('-','_').replace('/','7').replace('\\','I').replace('#','H').replace('(','C').replace(')','I').replace('[','I').replace(']','|').replace('}','I').replace('{','I').replace('@','a'));
            }
        }
		else super.handleEvent(e);
        return false;
     }
     else if(e.target instanceof Checkbox){
        if(e.id==1001){
            if( ((Checkbox)e.target).getLabel().equals("PDF") ){
                    if(((Checkbox)e.target).getState()) setFileType("pdf");
            }else if( ((Checkbox)e.target).getLabel().equals("HTML") ){
                    if(((Checkbox)e.target).getState()) setFileType("html");
            }else{
                    setFileType("ascii");
            }
                    //System.out.println(e.id+"setting pdf "+((Checkbox)e.target).getState());
        }
     }
     return true;
  }
  public void setFileType(String s){
		fmt = s;
  }
}
