package com.yonge.cooleshow.cms.config;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.vdurmont.emoji.EmojiParser;
import com.yonge.toolset.base.enums.BaseEnum;
import com.yonge.toolset.utils.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Date;

public class LocalFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {

	private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";

	@Override
	protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		return super.readInternal(clazz, inputMessage);
	}

	@Override
	protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

		OutputStream out = outputMessage.getBody();
		JsonUtil.getConfig().put(Date.class, new SimpleDateFormatSerializer(FORMAT));
		//JsonUtil.getConfig().put(String.class, new EmojiSerializer());
		String text = JsonUtil.toJSONString(obj, EnumFilter.instance, getFeatures());
		byte[] bytes = text.getBytes(getCharset());
		out.write(bytes);
	}
}

class EmojiSerializer implements ObjectSerializer{

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
		serializer.write(EmojiParser.parseToUnicode(object.toString()));
	}
	
}

class EnumFilter implements ValueFilter {

	public static EnumFilter instance = new EnumFilter();

	public EnumFilter() {
	}

	@Override
	public Object process(Object object, String name, Object value) {
		if (value == null || StringUtils.isBlank(value.toString())) {
			return value;
		}
		if (value instanceof BigDecimal || value instanceof Double || value instanceof Float) {
			return new BigDecimal(value.toString());
		}
		if (BaseEnum.class.isAssignableFrom(value.getClass())) {
			return ((BaseEnum<?, ?>) value).getCode();
		}
		return value;
	}
}
