package ash.util;

import java.util.List;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * スタックトレースをフィルタをかけて出力する。
 */
public class StackTrace {
	private static int traceLevel = 10;
	private static List<String> patterns = new ArrayList<String>();
	public static void setTraceLevel(int level) { traceLevel = level; }
	public static int getTraceLevel() { return traceLevel; }
	public static void addFilter(String pattern) { patterns.add(pattern); }
	public static void resetFilter() { patterns = new ArrayList<String>(); }
	public static void printFilters(PrintStream ps) {
		for(String pattern : patterns) ps.println(pattern);
	}

	public static void print(PrintStream ps, Throwable t) {
		StringWriter stringWriter= new StringWriter();
		t.printStackTrace(new PrintWriter(stringWriter));
		String stack = stringWriter.toString();
		try {
			BufferedReader br= new BufferedReader(new StringReader(stack));
			String line;
			int i = 0;
			while((line = br.readLine()) != null) {
				if(!filterLine(line)) {
					ps.println(line);
					if(++i > traceLevel) break;
				}
			}
		} catch (IOException e) {}
	}
	private static boolean filterLine(String line) {
		for(String pattern : patterns) {
			if(line.indexOf(pattern) > 0) return true;
		}
		return false;
	}
}
