
package com.dxhy.extend.websocket;

import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.extend.service.messagecontrol.ExtMessageControlService;

import lombok.extern.slf4j.Slf4j;

/**
 * 这个注解用于标识作用在类上，它的主要功能是把当前类标识成一个WebSocket的服务端 注解的值用户客户端连接访问的URL地址
 *
 * @author dxhy
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/{userName}")
public class ExtWebSocket extends AbstractController {

    public static final ConcurrentHashMap<String, Session> WEBSOCKET_USERINFO = new ConcurrentHashMap<>();
    /**
     * 用于存所有的连接服务的客户端，这个对象存储是安全的
     */
    private static final ConcurrentHashMap<String, ExtWebSocket> WEBSOCKETSET = new ConcurrentHashMap<>();
    private static ApplicationContext applicationContext;

    @Resource
    private ExtMessageControlService messageControlService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        ExtWebSocket.applicationContext = applicationContext;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName) {
        WEBSOCKETSET.put(userName, this);
        WEBSOCKET_USERINFO.put(userName, session);
        log.info("[WebSocket] 连接成功，当前连接人数为：={}", WEBSOCKETSET.size());
    }

    @OnClose
    public void onClose(Session session, @PathParam(value = "userName") String userName) {
        WEBSOCKETSET.remove(userName);
        WEBSOCKET_USERINFO.remove(userName);
        log.info("[WebSocket] 退出成功，当前连接人数为：={}", WEBSOCKETSET.size());
    }

    @OnMessage
    public void onMessage(Session session, String userMessage) {
        if (null != session && !StringUtils.isBlank(userMessage)) {
            log.info("[WebSocket] 收到消息：{}", userMessage);
            JSONObject jsonObj = JSONObject.parseObject(userMessage);
            messageControlService = applicationContext.getBean(ExtMessageControlService.class);
            int count = messageControlService.queryCount(jsonObj.getString("userName"));
            appointSending(session, Integer.toString(count));
        }
    }

    /**
     * 指定发送
     *
     * @param session
     *            session
     * @param msg
     *            信息
     */
    public void appointSending(Session session, String msg) {
        try {
            session.getBasicRemote().sendText(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
