package com.hys.app.framework.ws.impl;

import com.hys.app.framework.context.app.AppTypeEnum;
import com.hys.app.framework.util.DateUtil;
import com.hys.app.framework.ws.MessagePublisher;
import com.hys.app.framework.ws.SessionManager;
import com.hys.app.framework.ws.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * Author: Dawei
 * Datetime: 2022-07-18 15:27
 */
@Service
public class MessagePublisherImpl implements MessagePublisher {


    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private SessionManager sessionManager;



    @Override
    public boolean sendMessage(Message message) {

        Assert.notNull(message.getAppType(), "app type不能为空");
        Assert.notNull(message.getModuleType(), "module type不能为空");
        Assert.notNull(message.getUserId(), "userid 不能为空");

        AppTypeEnum appTypeEnum = message.getAppType();
        Long userId = message.getUserId();

        WebSocketSession webSocketSession = sessionManager.getSession(appTypeEnum, userId);

        if (webSocketSession == null) {
            return false;
        }

        message.setMsgTime(DateUtil.getDateline());
        String msgJson = toJson(message);

        TextMessage textMessage = new TextMessage(msgJson);
        try {

            logger.debug("send message:{}", message);
            webSocketSession.sendMessage(textMessage);

        } catch (IOException ex) {
            logger.error("websocket send message error", ex);
            return false;
        }
        return true;

    }



    /**
     * 将一个对象转换为json字符串，并应用PropertyNamingStrategy.SNAKE_CASE
     *
     * @param object
     * @return
     */
    private String toJson(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        String messageJson = "";
        try {
            messageJson = objectMapper.writeValueAsString(object);
        } catch (Exception ex) {
            logger.error("conver object to json string error", ex);
        }
        return messageJson;
    }

}
