package cn.axzo.msg.center.nimpush.payload.intent;

import cn.axzo.basics.common.exception.ServiceException;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.function.Consumer;

/**
 * @author yanglin
 */
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class IntentValue {

    private final Object value;

    private static final IntentValue NULL = new IntentValue(null);
    public static final IntentValue CONSTANT_SESSION_TYPE = new IntentValue("0");
    public static final IntentValue TYPE_SERVER = new IntentValue("server");
    public static final IntentValue TYPE_IM = new IntentValue("im");

    public static IntentValue create(Object value) {
        if (value == null) return NULL;
        return new IntentValue(value);
    }

    /**
     * 和app约定好了, intent里面都使用string类型的值
     */
    public void consume(Consumer<String> consumer) {
        if (value == null) return;
        consumer.accept(String.valueOf(value));
    }

    public IntentValue urlEncode() {
        if (value == null) return NULL;
        try {
            if (value instanceof String)
                return create(URLEncoder.encode((String) value, "UTF-8"));
            else
                throw new ServiceException("only string can be url encoded");
        } catch (UnsupportedEncodingException e) {
            log.warn("url encode failed, intent value: {}", value, e);
            throw new ServiceException(String.format("url encode failed, intent value: %s", value), e);
        }
    }

}