/*
 Eteria IRC Client, an RFC 1459 compliant client program written in Java.
 Copyright (C) 2000  Javier Kohen <jkohen at tough.com>
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 package ar.com.jkohen.util;
 
 import java.applet.Applet;
 import java.io.*;
 import java.net.*;
 import java.util.Enumeration;
 import java.util.Properties;
 
 
 public class NetworkConfiguration extends ConfigurationProperties
 {
 	private Applet app;
 	private String res_body;
 	
 	public NetworkConfiguration(Applet a, String s)
 	{
 		app = a;
 		read(s);
 	}
 	
 	public NetworkConfiguration(Applet a, String s, Properties defaults)
 	{
 		super(defaults);
 		app = a;
 		read(s);
 	}
 	
 	private void read(String name)
 	{
 		InputStream stream = null;
 		
 		if (name != null && name.length() > 0)
 		{
 			try
 			{
 				URLConnection uc = getURL(name).openConnection();
 				setUserId(uc);
 				if (uc != null)
 					stream = uc.getInputStream();
 				if (stream != null)
 				{
 					properties.load(stream);
 					stream.close();
 				}
 			}
 			catch (IOException ex)
 			{
 				ex.printStackTrace();
 			}
 		}
 	}
 	
 	private URL getURL(String file)
 	{
 		URL u = null;
 		URL base = app.getDocumentBase();
 		
 		try
 		{
 			u = new URL(file);
 		}
 		catch (MalformedURLException e1)
 		{
 			try
 			{
 				u = new URL(base.getProtocol(), base.getHost(), file);
 			}
 			catch (MalformedURLException e2)
 			{
 				System.err.println("Invalid URL : " + base.getProtocol() + base.getHost() + file);
 			}
 		}
 		
 		return(u);
 	}
 	
 	protected void setUserId(URLConnection uc) throws IOException
 	{
 		/* MS JVM doesn't manage Cookies, and ignore URLConnection.setRequestProperty("Cookie", String) */
 		
 		uc.setRequestProperty("X-Userid", app.getParameter("userid"));
 	}
 	
 	public void write(String name) throws IOException
 	{
 		OutputStreamWriter writer = null;
 
 		int res_code = -1;
 		String submit = "", res_msg = "";
 		
 		for (Enumeration e = keys(); e.hasMoreElements();)
 		{
 			String field = (String) e.nextElement();
 			String value = (String) get(field);
 
 			if (field != null)
 			{
 				if (submit.length() > 0)
 					submit += "&";
 				
 				submit += encode(field, "UTF8") + "=" + encode(value, "UTF8");
 			}
 		}
 
 		URLConnection cn = getURL(name).openConnection();
 		if (cn != null)
 		{
 			cn.setDoOutput(true);
 			
 			setUserId(cn);	
 			
 			writer = new OutputStreamWriter(cn.getOutputStream());
 			writer.write(submit);
 			writer.flush();
 
 			BufferedReader reader = new BufferedReader(new InputStreamReader(cn.getInputStream()));
 			String line;
 			while ((line = reader.readLine()) != null)
 				res_body += line + "\n";
 			reader.close();
 		}
 		writer.close();
 	}
 	
 	public String getMessageBody()
 	{
 		return(res_body);
 	}
 	
 	public static String encode(String data, String charset) throws UnsupportedEncodingException
 	{
 		String enc = "";
 		if (data != null)
 		{
 			char chars[] = data.toCharArray();
 			char c = 0;
 			for (int i = 0; i < chars.length; i++)
 			{
 				c = chars[i];
 
 				if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
 				{
 					enc += c;
 				}
 				else if (c == ' ')
 				{
 					enc += '+';
 				}
 				else
 				{
 					char s[] = { c };
 					byte ch[] = new String(s).getBytes(charset);
 					char hex[] = { 0, 0 };
 					for (int j = 0; j < ch.length; j++)
 					{
 						hex[0] = Character.forDigit((ch[j] >> 4) & 0xF, 16);
 						hex[1] = Character.forDigit(ch[j] & 0xF, 16);
 						enc += '%' + new String(hex);
 					}
 				}
 			}
 		}
 		
 		return(enc);
 	}
 }