/*
 * 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 java.io.IOException;

/**
 * Translates escaped Unicode values of the form \\u+\d\d\d\d back to 
 * Unicode. It supports multiple 'u' characters and will work with or 
 * without the +.
 * 
 */
public class UnicodeUnescaper extends CharSequenceTranslator {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int translate(final CharSequence input, final int index, final Appendable out) throws IOException {
		if (input.charAt(index) == '\\' && index + 1 < input.length() && input.charAt(index + 1) == 'u') {
			// consume optional additional 'u' chars
			int i = 2;
			while (index + i < input.length() && input.charAt(index + i) == 'u') {
				i++;
			}

			if (index + i < input.length() && input.charAt(index + i) == '+') {
				i++;
			}

			if (index + i + 4 <= input.length()) {
				// Get 4 hex digits
				final CharSequence unicode = input.subSequence(index + i, index + i + 4);

				try {
					final int value = Integer.parseInt(unicode.toString(), 16);
					out.append((char)value);
				}
				catch (final NumberFormatException nfe) {
					throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe);
				}
				return i + 4;
			}
			else {
				throw new IllegalArgumentException("Less than 4 hex digits in unicode value: '"
						+ input.subSequence(index, input.length()) + "' due to end of CharSequence");
			}
		}
		return 0;
	}
}
