package com.xxxxxxx.drvpp.fw.common.test;

import java.io.File;

public class TestUtil {
	private String testRoot = "./testRoot/";

	private static class TestUtilHolder {
		private static final TestUtil instance = new TestUtil();
	}

	public static TestUtil getInstance() {
		return TestUtilHolder.instance;
	}

	private TestUtil() {

	}

	public File newFile(String filename) {
		File dir = getDir();
		return new File(dir, filename);
	}

	public File getDir() {
		String methodName = getFullMethodName();
		String dirName = methodName.replace('.', '/');
		File dir = new File(testRoot, dirName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	public String getMethodName() {
		StackTraceElement ste = getStackTraceElement();
		return ste.getMethodName();
	}

	public String getFullMethodName() {
		StackTraceElement ste = getStackTraceElement();
		return ste.getClassName() + "." + ste.getMethodName();
	}

	private StackTraceElement getStackTraceElement() {
		try {
			throw new Exception();
		} catch (Exception e) {
			StackTraceElement[] ste = e.getStackTrace();
			StackTraceElement st = null;
			for (int i = 0; i < ste.length; i++) {
				String name = ste[i].getClassName();
				if (name.substring(name.length() - 4).equals("Test")) {
					st = ste[i];
					for (i = i + 1; i < ste.length; i++) {
						name = ste[i].getClassName();
						if (name.substring(name.length() - 4).equals("Test")) {
							st = ste[i];
						} else {
							break;
						}
					}
					break;
				}
			}
			return st;
		}
	}

	public String getTestRoot() {
		return testRoot;
	}

	public void setTestRoot(String testRoot) {
		this.testRoot = testRoot;
	}
}
