package com.vetti.common.international;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.vetti.common.config.InternationalProperties;
import com.vetti.common.utils.spring.SpringUtils;

import java.io.IOException;

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

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

        InternationalResourceGetter iTextGetter = SpringUtils.getBean(InternationalResourceGetter.class);
        InternationalProperties iProperties = SpringUtils.getBean(InternationalProperties.class);
        if (null == iTextGetter || !iProperties.isEnable()) {
            gen.writeString(value);
            return;
        }

        // 获取客户语言环境
        String lang = iProperties.getLang();
        if (!StrUtil.isBlank(lang)) {
            String itext = iTextGetter.getText(value, lang);
            if (null == itext) {
                gen.writeNull();
            } else {
                gen.writeString(itext);
            }
        } else {
            gen.writeString(value);
        }
    }
}
