/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.lang.escape;

import nuts.core.lang.Chars;
import nuts.core.lang.Strings;

import java.io.IOException;

// TODO: Create a parent class - 'SinglePassTranslator' ?
// It would handle the index checking + length returning,
// and could also have an optimization check method.
public class CsvEscaper extends CharSequenceTranslator {
	private static final char CSV_DELIMITER = ',';
	private static final char CSV_QUOTE = '"';
	private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
	private static final char[] CSV_SEARCH_CHARS = new char[] { CSV_DELIMITER, CSV_QUOTE,
			Chars.CR, Chars.LF };

	@Override
	public int translate(CharSequence input, int index, Appendable out) throws IOException {

		if (index != 0) {
			throw new IllegalStateException("CsvEscaper should never reach the [1] index");
		}

		if (Strings.containsNone(input.toString(), CSV_SEARCH_CHARS)) {
			out.append(input);
		}
		else {
			out.append(CSV_QUOTE);
			out.append(Strings.replace(input.toString(), CSV_QUOTE_STR, CSV_QUOTE_STR
					+ CSV_QUOTE_STR));
			out.append(CSV_QUOTE);
		}
		return input.length();
	}
}
