package cn.axzo.msg.center.api.request;

import cn.axzo.basics.common.util.AssertUtil;
import cn.axzo.msg.center.service.enums.MnsChannel;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author yanglin
 */
@Slf4j
@Setter
@Getter
public class ExpansionInfo {

    /**
     * 扩展参数.
     * <p/> 这个是很早之前就有的字段了, 不确定是否有其它人在使用, 因此保留为String类型
     */
    private String expansion;

    /**
     * 指定短信发送渠道
     * <p/>不指定的情况下使用默认渠道, 当前为阿里云
     */
    public void setChannel(MnsChannel channel) {
        AssertUtil.notNull(channel, "channel must not be null");
        addExpansion("assign_channel", channel.getCode());
    }

    public void setVariableAbbreviation(VariableAbbreviation abbreviation) {
        AssertUtil.notNull(abbreviation, "abbreviation must not be null");
        addExpansion("abbreviation", abbreviation);
    }

    public VariableAbbreviation getVariableAbbreviationOrDefault() {
        JSONObject obj = parseExpansion();
        VariableAbbreviation abbreviation = obj.getObject("abbreviation", VariableAbbreviation.class);
        return abbreviation == null ? VariableAbbreviation.defaultAbbreviate() : abbreviation;
    }

    public void addExpansion(String key, Object value) {
        JSONObject obj = parseExpansion();
        obj.put(key, value);
        expansion = obj.toJSONString();
    }

    public JSONObject parseExpansion() {
        JSONObject obj = null;
        if (StringUtils.isNotBlank(expansion)) {
            try {
                obj = JSONObject.parseObject(expansion);
            } catch (Exception e) {
                log.warn("parse expansion error, expansion={}", expansion, e);
            }
        }
        if (obj == null)
            obj = new JSONObject();
        return obj;
    }

}