package com.goafanti.core.websocket;

import com.goafanti.common.utils.LoggerUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

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

@Service
public class SystemWebSocketHandler implements WebSocketHandler {
	

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

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String userId = (String) 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();
		}
		users.remove(session);
		LoggerUtils.debug(getClass(), "websocket: error");
	}

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

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

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(TextMessage message) {
		for (String 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(String userId, TextMessage message) {
		WebSocketSession user = users.get(userId);
		if (user != null) {
			try {
				if (user.isOpen()) {
					user.sendMessage(message);
					LoggerUtils.debug(getClass(), "用户" + userId + "websocket通知消息成功");
				}
			} catch (IOException e) {
				LoggerUtils.error(getClass(), "用户" + userId + "websocket通知异常", e);
			}
		}
	}

}