package com.dd.admin.business.webSocket.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;

public class TioUtil {


    /**
     * 快速生成WsResponse
     * @param action
     * @param body
     * @return
     */
    public static WsResponse madeWsResponse(String handlerType, Object body){
//        String responseMsg = JSON.toJSONString(body);
//        System.out.println(responseMsg);
        // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 开启美化输出（格式化）功能
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        // 将List<Person>对象转换为JSON字符串
        try {
            String responseMsg = objectMapper.writeValueAsString(body);
            System.out.println(responseMsg);
            return WsResponse.fromText(responseMsg,"utf-8");

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean sendMessage(ChannelContext con, String handlerType, Object body){
        WsResponse weResponse = madeWsResponse(handlerType,body);
        return Tio.send(con,weResponse);
    }
}
