/*
 * 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.Arrays;

import java.io.IOException;

/**
 * Executes a sequence of translators one after the other. Execution ends whenever 
 * the first translator consumes codepoints from the input.
 * 
 */
public class AggregateTranslator extends CharSequenceTranslator {

	private final CharSequenceTranslator[] translators;

	/**
	 * Specify the translators to be used at creation time.
	 * 
	 * @param translators CharSequenceTranslator array to aggregate
	 */
	public AggregateTranslator(final CharSequenceTranslator... translators) {
		this.translators = Arrays.clone(translators);
	}

	/**
	 * The first translator to consume codepoints from the input is the 'winner'. Execution stops
	 * with the number of consumed codepoints being returned. {@inheritDoc}
	 */
	@Override
	public int translate(final CharSequence input, final int index, final Appendable out) throws IOException {
		for (final CharSequenceTranslator translator : translators) {
			final int consumed = translator.translate(input, index, out);
			if (consumed != 0) {
				return consumed;
			}
		}
		return 0;
	}

}
