package project.common;

import java.util.StringJoiner;


/**
 * TSVユーティリティ
 * @author Tadashi Nakayama
 */
public final class TsvUtil {

	/**
	 * コンストラクタ
	 */
	private TsvUtil() {
		throw new AssertionError();
	}

	/**
	 * TSV文字列を配列化
	 * @param val TSV文字列
	 * @return 文字列配列
	 */
	public static String[] toArray(final String val) {
		final String[] ret = val.split("\t", -1);
		for (int i = 0; i < ret.length; i++) {
			if (1 < ret[i].length() && ret[i].startsWith("\"") && ret[i].endsWith("\"")) {
				ret[i] = ret[i].substring("\"".length(), ret[i].length() - "\"".length());
				ret[i] = ret[i].replace("\"\"", "\"");
			}
		}
		return ret;
	}

	/**
	 * TSV文字列化
	 * @param vals 文字列配列
	 * @return TSV文字列
	 */
	public static String toTsv(final String... vals) {
		final StringJoiner sj = new StringJoiner("\t");
		for (int i = 0; vals != null && i < vals.length; i++) {
			sj.add(toTsvValue(vals[i], true));
		}
		return sj.toString();
	}

	/**
	 * TSV値化
	 * @param val 文字列
	 * @return TSV値
	 */
	public static String toTsvValue(final String val) {
		return toTsvValue(val, true);
	}

	/**
	 * TSV値化
	 * @param val 文字列
	 * @param lf LFのみフラグ
	 * @return TSV値
	 */
	public static String toTsvValue(final String val, final boolean lf) {
		final StringBuilder sb = new StringBuilder();

		String quote = "";
		for (int i = 0; val != null && i < val.length(); i = val.offsetByCodePoints(i, 1)) {
			if (val.codePointAt(i) == '"') {
				quote = "\"";
				sb.append("\"");
			} else if (val.codePointAt(i) == ',') {
				quote = "\"";
			} else if (val.codePointAt(i) == '\r') {
				if (lf) {
					continue;
				}
				quote = "\"";
			} else if (val.codePointAt(i) == '\n') {
				quote = "\"";
			} else if (val.codePointAt(i) == '\t') {
				sb.append(" ");
				continue;
			}
			sb.appendCodePoint(val.codePointAt(i));
		}

		return quote + sb.append(quote).toString();
	}
}
