import java.net.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.http.*;

public class Util extends Object {
  public static String br(String s) {
    StringBuffer sb = new StringBuffer(s);

    int l;
    while((l = sb.toString().indexOf('\n')) != -1) {
      sb.setCharAt(l, '<');
      sb.insert(l+1, "br>");
    }

    return sb.toString();
  }

  public static String getQueryValue(HttpServletRequest req, String name) throws InternalException {
    String qs = req.getQueryString();
    if(qs == null)
      throw new InternalException("name not found in query string: " + name);
    Hashtable h = HttpUtils.parseQueryString(qs);
    String[] c = (String[])h.get(name);
    if(c == null)
      throw new InternalException("name not found in query string: " + name);

    return c[0];
  }

  public static String getCnum(HttpServletRequest req) throws InternalException {
    String qs = req.getQueryString();
    if(qs == null)
      throw new InternalException("missing employee number (cnum)");
    Hashtable h = HttpUtils.parseQueryString(qs);
    String[] c = (String[])h.get("cnum");
    if(c == null)
      throw new InternalException("missing employee number (cnum)");

    return c[0];
  }

  public static String getCnumCcode(HttpServletRequest req) throws InternalException {
    String qs = req.getQueryString();
    if(qs == null)
      throw new InternalException("missing employee number (cnum)");
    Hashtable h = HttpUtils.parseQueryString(qs);
    String[] cn = (String[])h.get("cnum");
    if(cn == null)
      throw new InternalException("missing employee number (cnum)");
    String[] cc = (String[])h.get("ccode");
    if(cc == null)
      throw new InternalException("missing employee country code (ccode)");

    return cn[0] + cc[0];
  }

  public static String getCookieValue(HttpServletRequest req, String name) throws InternalException {
    return getCookieValue(req, name, true);
  }

  public static String getCookieValue(HttpServletRequest req, String name, boolean fake) throws InternalException{
    if(!fake) {
      throw new InternalException("cannot use native JSDK Cookie methods");
      //      Cookie[] cook = req.getCookies();
      //      if(cook == null)
      //	return null;
      //      for(int i = 0; i < cook.length; i++) {
      //	if(cook[i].getName().equals(name))
      //	  return cook[i].getValue();
      //      }
      //      return null;
    } else {
      String cookieString;
      cookieString = req.getHeader("COOKIE");
      if(cookieString == null)
	cookieString = req.getHeader("Cookie");
      if(cookieString == null)
	cookieString = req.getHeader("cookie");
      if(cookieString == null)
	return null;

      StringTokenizer cookieParser = new StringTokenizer(cookieString, ";\n");
      String nvp, cname, cvalue;
      int l;
      while(cookieParser.hasMoreTokens()) {
	nvp = cookieParser.nextToken();
	if(nvp.charAt(0) == ' ')
	  nvp = new String(nvp.substring(1));
	l = nvp.indexOf('=');
	if(l == -1)
	  continue;
	cname = new String(nvp.substring(0, l));
	cvalue = new String(nvp.substring(l+1));
	if(cname.equals(name))
	  return cvalue;
      }
      return null;
    }
  }

  public static void setCookie(HttpServletResponse res, String name, String value, Date exp, String path, String domain, boolean secure) {
    String cstring = new String(name + "=" + value);
    if(exp != null) {
      SimpleDateFormat simpleDate = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'");
      cstring += "; expires=" + simpleDate.format(exp);
    }
    if(path != null)
      cstring += "; path=" + path;
    if(domain != null)
      cstring += "; domain=" + domain;
    if(secure)
      cstring += "; secure";
    res.setHeader("Set-Cookie", cstring);
    //    System.out.println(cstring);
  }

  public static String getHrefLink(String h) throws InternalException {
    int l = h.toLowerCase().indexOf("href");
    if(l != -1) {
      int s = h.indexOf("\"", l);
      if(s != -1) {
	int e = h.indexOf("\"", s + 1);
	if(e != -1) {
	  return h.substring(s + 1, e);
	}
      }
    }
    throw new InternalException("bad URL format in getHrefLink: " + h);
  }

  public static String getHrefText(String h) throws InternalException {
    int s = h.indexOf(">");
    if(s != -1) {
      int e = h.lastIndexOf("<");
	if(e > s) {
	  return h.substring(s + 1, e);
	}
    }
    throw new InternalException("bad URL format in getHrefText: " + h);
  }

  public static Vector readURL(String url) throws APIException, IOException, URLFileException {
    URL p;
    URLConnection page;
    InputStream in;
    DataInputStream din;
    Vector v = null;
    int numlines;

    try {
      p = new URL(url);
      page = p.openConnection();
      in = page.getInputStream();
      din = new DataInputStream(in);

      String line;
      numlines = 0;
      while((line = din.readLine()) != null) {
	if(numlines == 0) {    // <PRE> line
	  ;
	} else if(numlines == 1) {
	  int ecode;
	  try {
	    ecode = Integer.parseInt(line);
	  }
	  catch (NumberFormatException nf) {
	    throw new APIException("readURL: " + line);
	  }
	  if(ecode != 0)
	    throw new APIException(ecode, "readURL: error # " + ecode);
	} else if(line.startsWith("//")) {
	  break;
	} else {
	  if(v == null)
	    v = new Vector();
	  v.addElement(line);
	}
	numlines++;
      }
    }
    catch (FileNotFoundException fnf) {
      throw new URLFileException(fnf.getMessage());
    }
    //    System.out.println("readURL finishing, lines: " + numlines);

    return v;
  }
}
