package org.bench4q.recorder.httpcapture;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

public class Utils {
	public static final String SPACE = "                                                                                ";
	private static final Logger log = Logger.getLogger(Utils.class);

	public static File saveHTML(String htmlFileName, String str, String dir_str) {
		if (str == null) {
			log.error("Argument is null: EditorPane.saveHTML()");
			return null;
		}
		File dir, htmlFile;
		if (dir_str == null) {
			dir = new File("Tempfiles");
		} else {
			dir = new File(dir_str);
		}
		dir.mkdir();
		try {
			htmlFile = new File(dir, htmlFileName);
			if (htmlFile.exists()) {
				htmlFile.delete();
				log.warn("deleting duplicated file: " + htmlFileName);
			}
			htmlFile.createNewFile();
			PrintWriter writer = new PrintWriter(new FileWriter(htmlFile));
			writer.print(str);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return htmlFile;
	}

	public static String[] splitString(String str, String delim) {
		StringTokenizer st = new StringTokenizer(str, delim);
		String[] res = new String[st.countTokens()];
		int i = 0;
		while (st.hasMoreTokens()) {
			res[i] = st.nextToken();
			i++;
		}
		return res;
	}

	public static String replace(String str, String search, String replace) {
		int pos = str.indexOf(search);
		if (pos == -1)
			return str;
		StringBuffer buff = new StringBuffer(str.length() + 32);
		int start = 0;
		while ((pos != -1) && (start < str.length())) {
			buff.append(str.substring(start, pos));
			buff.append(replace);

			start = pos + search.length();
			if (start < str.length())
				pos = str.indexOf(search, start);
		}
		if (start < str.length())
			buff.append(str.substring(start));

		return buff.toString();
	}

	public static List<Param> getParams(String query) {
		List<Param> paramList = new ArrayList<Param>();
		if (query != null) {
			query = query.trim();
			log.debug("  parsing: " + query);
			String[] items = splitString(query, "&");
			for (int i = 0; i < items.length; i++) {
				int pos = items[i].indexOf("=");
				if (pos != -1) {
					Param p = new Param();
					paramList.add(p);
					p.name = items[i].substring(0, pos);
					if (pos < items[i].length() - 1)
						p.value = items[i].substring(pos + 1);
					else
						p.value = "";
				}
			}
		}
		return paramList;
	}

	public static class SilentException extends Exception {
		private static final long serialVersionUID = 3172942039967787899L;

		public SilentException() {
			super();
		}
	}

	public static class UserException extends Exception {
		private static final long serialVersionUID = -7337004995296463936L;

		public UserException(String s) {
			super();
		}
	}
}
