package com.goafanti.core.websocket;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.goafanti.common.utils.LoggerUtils;

public class SystemWebSocketHandler implements WebSocketHandler {

	private static final Map<Long, WebSocketSession> users = new ConcurrentHashMap<>();

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		Long userId = (Long) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
		if (userId != null) {
			users.put(userId, session);
			LoggerUtils.debug(getClass(), "添加用户websocket：" + userId);
		}
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		LoggerUtils.debug(getClass(), message.getPayload().toString());
	}

	@SuppressWarnings("unlikely-arg-type")
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		LoggerUtils.debug(getClass(), "websocket: " + users.remove(session) + "关闭");
	}

	@SuppressWarnings("unlikely-arg-type")
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		LoggerUtils.debug(getClass(), "websocket: " + users.remove(session) + "关闭");
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(TextMessage message) {
		for (Long userId : users.keySet()) {
			WebSocketSession user = users.get(userId);
			try {
				if (user.isOpen()) {
					user.sendMessage(message);
				}
			} catch (IOException e) {
				LoggerUtils.error(getClass(), "用户:" + userId + "websocket通知异常", e);
			}
		}
	}

	/**
	 * 给某个用户发送消息
	 *
	 * @param userId
	 * @param message
	 */
	public void sendMessageToUser(Long userId, TextMessage message) {
		WebSocketSession user = users.get(userId);
		if (user != null) {
			try {
				if (user.isOpen()) {
					user.sendMessage(message);
				}
			} catch (IOException e) {
				LoggerUtils.error(getClass(), "用户" + userId + "websocket通知异常", e);
			}
		}
	}
}