package com.yihu.hos.interceptor;

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

/**
 * @created Airhead 2016/11/14.
 */
public class LocalContext {
    private static final ThreadLocal<LocalContext> LOCAL = new ThreadLocal<LocalContext>() {
        @Override
        protected LocalContext initialValue() {
            return new LocalContext();
        }
    };
    private static final Map<String, String> attachments = new HashMap<>();

    public static LocalContext getContext() {
        return LOCAL.get();
    }

    public static void removeContext() {
        LOCAL.remove();
    }

    public String getAttachment(String key) {
        return this.attachments.get(key);
    }

    public LocalContext setAttachment(String key, String value) {
        if (value == null) {
            this.attachments.remove(key);
        } else {
            this.attachments.put(key, value);
        }

        return this;
    }

    public LocalContext removeAttachment(String key) {
    this.attachments.remove(key);
        return this;
    }

    public Map<String, String> getAttachments() {
        return this.attachments;
    }

    public LocalContext setAttachments(Map<String, String> attachment) {
        this.attachments.clear();
        if (attachment != null && attachment.size() > 0) {
            this.attachments.putAll(attachment);
        }

        return this;
    }

    public void clearAttachments() {
        this.attachments.clear();
    }
}
