package com.ag.web.websocket.service;

import com.ag.log.RemqMsgCustom;
import com.ag.log.service.impl.RemqMsgCustomServiceImpl;
import com.ag.web.websocket.AgWebSocketHander;
import com.alibaba.fastjson.JSON;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

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

@Service
public class AgSktService  {
    @Autowired
    private RemqMsgCustomServiceImpl remqMsgCustomService;

    private static final Logger LOGGER = LoggerFactory.getLogger(AgSktService.class);

    private ConcurrentHashMap<String, WebSocketSession> userSession
            = AgWebSocketHander.getUserSession();

    public void sendMsgToUser(String userId, RemqMsgCustom socketBean) {
        remqMsgCustomService.save(socketBean);
        if (userId != null && userSession.containsKey(userId)) {
            try {
                if (userSession.get(userId).isOpen()) {
                    userSession.get(userId).sendMessage(new TextMessage(JSON.toJSONString(socketBean)));
                }
            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.error(e.getLocalizedMessage());
                throw new RuntimeException(e.getCause());
            }
        }
    }
}