package com.winsea.svc.common.international;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.yh.saas.common.support.util.ContextWrapper;

import java.io.IOException;

/**
 * 国际化序列化器
 * 
 * @author SunTianjun
 */
public class InternationalSerializer extends JsonSerializer<String> {

	@Override
	public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
		if (null == value) {
			gen.writeNull();
			return;
		}

		InternationalResourceProviderAdapter iResourceProvider = getInternationalResourceProvider();
		if (null == iResourceProvider) {
			gen.writeString(value);
			return;
		}

		// 获取客户语言环境
		String lang = ContextWrapper.getApplicationContext().getBean(InternationalProperties.class).getLang();
		if (!StringUtils.isEmpty(lang)) {
			String itext = iResourceProvider.getText(value, lang);
			if (StringUtils.isEmpty(itext)) {
				gen.writeString(value);
			} else {
				gen.writeString(itext);
			}
		} else {
			gen.writeString(value);
		}
	}

	private InternationalResourceProviderAdapter getInternationalResourceProvider() {
		try {
			return ContextWrapper.getApplicationContext().getBean(InternationalResourceProviderAdapter.class);
		} catch (Exception ex) {
			return null;
		}
	}
}
