package tech.starwin.utils.event_bus;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Sikang on 2017/3/16.
 * EventBus消息载体
 */

public class EventMessage {
    /**
     * 消息类型
     */
    public int what;

    /**
     * String类型消息
     */
    public String msg = "";

    /**
     * Object类型消息
     */
    public Object obj;

    /**
     * 多参数消息
     */
    private Map<String, Object> params;

    /**
     * 需要过滤的目标
     */
    public String filters = "";

    /**
     * 指定发送的目标
     */
    public String targets = "";

    public EventMessage() {

    }

    public EventMessage(int what, String msg) {
        this.what = what;
        this.msg = msg;
    }

    /**
     * 添加自定义参数
     */
    public void put(String key, Object value) {
        if (params == null)
            params = new HashMap<>();
        params.put(key, value);
    }

    public void addFilter(Class clz) {
        filters += clz.getName() + ";";
    }

    public void addTarget(Class clz) {
        targets += clz.getName() + ";";
    }

    /**
     * 是否是被过滤的目标
     */
    public <T> boolean isFilter(T t) {
        return filters.contains(t.getClass().getName());
    }

    /**
     * 是否是被指定的目标
     */
    public <T> boolean isTraget(T t) {
        //如果没有指定目标，默认全局发送
        if (TextUtils.isEmpty(targets))
            return true;
        return targets.contains(t.getClass().getName());
    }

    public String get(String key) {
        if (params != null) {
            Object value = params.get(key);
            if (value != null && value instanceof String)
                return (String) value;
        }
        return "";
    }

    public int getInt(String key, int defaultValue) {
        if (params != null) {
            Object value = params.get(key);
            if (value != null && value instanceof Integer)
                return (int) value;
        }
        return defaultValue;
    }

    public float getFloat(String key, float defaultValue) {
        if (params != null) {
            Object value = params.get(key);
            if (value != null && value instanceof Float)
                return (float) value;
        }
        return defaultValue;
    }

    public double getDouble(String key, double defaultValue) {
        if (params != null) {
            Object value = params.get(key);
            if (value != null && value instanceof Double)
                return (double) value;
        }
        return defaultValue;
    }

}
