package com.dashitech.callcenter.webSocket.core;

import org.atmosphere.cpr.AtmosphereResource;

import java.util.Map;

/**
 * Websocket发送消息工具类
 * Created by CX on 2018/8/9 0022.
 */
public class WebSocketSender {
    private SessionCache cache;

    public SessionCache getCache() {
        return cache;
    }

    public void setCache(SessionCache cache) {
        this.cache = cache;
    }

    /**
     * 检查是否有浏览器连接进来，是否已经有缓存
     *
     * @return true有
     */
    public boolean isReady() {
        if (this.cache != null) {
            return true;
        }
        return false;
    }

    /**
     * 给指定浏览器发送消息
     *
     * @param identity 浏览器唯一标识
     * @param message  消息
     * @throws Exception
     */
    public void identityMessage(String identity, String message) throws Exception {
        if (this.cache != null && this.cache.contains(identity)) {
            AtmosphereResource atmosphereResource = this.cache.get(identity);
            if(atmosphereResource!=null && !atmosphereResource.isCancelled()){
                atmosphereResource.getResponse().getWriter().write(message);
            }else {
                cache.removeByUUID(identity);
            }
        }
    }

    /**
     * 广播给所有缓存浏览器发送消息
     *
     * @param message 消息
     * @throws Exception
     */
    public void identityBroadcastMessage(String message) throws Exception {
        if (this.cache != null) {
            for (Map.Entry<String, AtmosphereResource> entry : cache.getIndentityCache().entrySet()) {
                if(!entry.getValue().isCancelled()){
                    entry.getValue().getResponse().getWriter().write(message);
                }else {
                    cache.removeByUUID(entry.getKey());
                }
            }
        }
    }
}
