package com.style24.core.support.text;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.text.translate.AggregateTranslator;
import org.apache.commons.text.translate.CharSequenceTranslator;
import org.apache.commons.text.translate.EntityArrays;
import org.apache.commons.text.translate.LookupTranslator;

import com.fasterxml.jackson.core.SerializableString;
import com.fasterxml.jackson.core.io.CharacterEscapes;
import com.fasterxml.jackson.core.io.SerializedString;

@SuppressWarnings("serial")
public class TscHtmlCharacterEscapes extends CharacterEscapes {

	private final int[] asciiEscapes;

	private final CharSequenceTranslator translator;

	public TscHtmlCharacterEscapes() {
		// XSS 방지 처리할 특수 문자 지정
		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;

		Map<CharSequence, CharSequence> lookupMap = new HashMap<>();
		lookupMap.put("(", "&#40");
		lookupMap.put(")", "&#41");
		lookupMap.put("#", "&#35");
		lookupMap.put("\\", "&#39");
		Map<CharSequence, CharSequence> CUSTOM_ESCAPE = Collections.unmodifiableMap(lookupMap);

		// XSS 방지 처리 특수문자 인코딩 값 지정
		this.translator = new AggregateTranslator(
			new LookupTranslator(EntityArrays.BASIC_ESCAPE), // <, >, &, "는 여기에 포함
			new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE),
			new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE),
			new LookupTranslator(CUSTOM_ESCAPE));
	}

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

	@Override
	public SerializableString getEscapeSequence(int ch) {
		return new SerializedString(translator.translate(Character.toString((char)ch)));
		// 커스터마이징이 필요 없다면 아래걸 그대로 사용
//		return new SerializedString(StringEscapeUtils.escapeHtml4(Character.toString((char)ch)));
	}

}