package com.interplug.qcast.config.json;

import com.fasterxml.jackson.core.SerializableString;
import com.fasterxml.jackson.core.io.CharacterEscapes;
import com.fasterxml.jackson.core.io.SerializedString;
import org.apache.commons.lang3.StringEscapeUtils;

/**
 * <pre>
 * xss 방어
 *
 * </pre>
 *
 * @author KimYoungHyun (youngh.kim@kt.com)
 */
public class HtmlCharacterEscapes extends CharacterEscapes {

	private static final long serialVersionUID = 2432838078852295950L;
	private final int[] asciiEscapes;

	/**
	 * xss 방지를 위해 escape 처리
	 */
	public HtmlCharacterEscapes() {
		asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON();
		asciiEscapes['<'] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes['>'] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes['&'] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes['\''] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes['\"'] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes['('] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes[')'] = CharacterEscapes.ESCAPE_CUSTOM;
		asciiEscapes['#'] = CharacterEscapes.ESCAPE_CUSTOM;
	}

	@Override
	public int[] getEscapeCodesForAscii() {
		return asciiEscapes;
	}

	@Override
	public SerializableString getEscapeSequence(int ch) {
		SerializedString serializedString = null;
		char charAt = (char) ch;

		// emoji(Emoticons) character
		if (Character.isHighSurrogate(charAt) || Character.isLowSurrogate(charAt)) {
			StringBuilder sb = new StringBuilder();
			sb.append("\\u");
			sb.append(String.format("%04x", ch));
			serializedString = new SerializedString(sb.toString());
		} else {
			serializedString = new SerializedString(StringEscapeUtils.escapeHtml4(Character.toString(charAt)));
		}

		return serializedString;
	}

}
