package hiro.yoshioka.ast.sql.util;

import java.util.ArrayList;

public class StringFormat {
	public static int MODE_AVG_LENGTH = 1;

	public static int MODE_MAX_LENGTH = 2;

	public static void main(String[] args) {
		String[] targets = { "tanaka", "gozaresu", "mikimoto yoshida", "niko",
				"a", "0", "decode(hoge,pito)","  long_long_name_column", "column8, ",
				"case if(select  * from date())", "55" };
		String[] ret = format(true, MODE_MAX_LENGTH, 2, 80, targets, ",");
		for (int i = 0; i < ret.length; i++) {
			System.out.println(ret[i]);
		}
		System.out.println("-------------------------------------");
		ret = format(false, MODE_MAX_LENGTH, 2, 12, targets, ",");
		for (int i = 0; i < ret.length; i++) {
			System.out.println(ret[i]);
		}
	}

	public static String[] format(boolean left, int mode, int col_num,
			int max_col_len, String[] targets, String sufix) {
		ArrayList<String> retList = new ArrayList<String>();

		int row_num = targets.length / col_num;
		int last_col_num = targets.length % col_num;
		String apattern = "";
		if (last_col_num > 0) {
			row_num++;
		} else {
			last_col_num = col_num;
		}

		int len = 0;
		if (mode == MODE_AVG_LENGTH) {
			len = getAvgLength(targets);
		} else if (mode == MODE_MAX_LENGTH) {
			len = getMaxLength(targets);
		}
		len += sufix.length();

		if (len > max_col_len) {
			len = max_col_len;
		}

		if (left) {
			apattern = "%-" + len + "s";
		} else {
			apattern = "%" + len + "s";
		}

		StringBuffer pattern = new StringBuffer();
		Object[] args = new Object[col_num];
		int tIdx = 0;
		for (int i = 0; i < row_num - 1; i++) {
			if (i == 0) {
				for (int j = 0; j < col_num; j++) {
					pattern.append(apattern);
				}
			}
			for (int j = 0; j < col_num; j++) {
				args[j] = targets[tIdx++] + sufix;
			}
			retList.add(String.format(pattern.toString(), args));
		}
		pattern = new StringBuffer();
		args = new Object[last_col_num];
		for (int i = 0; i < last_col_num; i++) {
			pattern.append(apattern);
			if (i == last_col_num - 1) {
				args[i] = targets[tIdx++];
			} else {
				args[i] = targets[tIdx++] + sufix;
			}
		}
		retList.add(String.format(pattern.toString(), args));

		return retList.toArray(new String[0]);
	}

	public static int getMaxLength(String[] targets) {
		int len = 0;
		for (int i = 0; i < targets.length; i++) {
			if (len < targets[i].length()) {
				len = targets[i].length();
			}
		}
		return len;
	}

	public static int getAvgLength(String[] targets) {
		int sum = 0;
		for (int i = 0; i < targets.length; i++) {
			sum += targets[i].length();
		}
		return sum / targets.length;
	}
}
