package net.northking.cctp.upperComputer.utils;

import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.upperComputer.webSocket.entity.CmdRequest;
import net.northking.cctp.upperComputer.webSocket.entity.CmdResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;

public class SessionUtils {

    private final static Logger logger = LoggerFactory.getLogger(SessionUtils.class);

    public static void sendMessageInitiative(Session session,String cmd,String serial,Map<String, Object> result,String message){
        CmdResponse response = CmdResponse.buildForInitiative(cmd).withSerial(serial).withMessage(message).finished().withData(result);
        SessionUtils.sendMessage(session, JSONObject.toJSONString(response));
    }

    public static void sendSuccessData(Session session, CmdRequest request, Object result, String message){
        CmdResponse response = CmdResponse.build(request).success(result).finished().withMessage(message);
        SessionUtils.sendMessage(session, JSONObject.toJSONString(response));
    }

    public static void sendContinuousData(Session session, CmdRequest request, Map<String, Object> result, String message){
        CmdResponse response = CmdResponse.build(request).success(result).continuous().withMessage(message);
        SessionUtils.sendMessage(session, JSONObject.toJSONString(response));
    }

    public static void sendContinuousData(Session session, CmdRequest request, Object result, String message){
        CmdResponse response = CmdResponse.build(request).success(result).continuous().withMessage(message);
        SessionUtils.sendMessage(session, JSONObject.toJSONString(response));
    }

    public static void sendFailureMessage(Session session,CmdRequest request,String message){
        CmdResponse response = CmdResponse.build(request).finished().fail(message);
        SessionUtils.sendMessage(session, JSONObject.toJSONString(response));
    }

    public static void sendMessage(Session session,String message){
        synchronized (session) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IllegalStateException e) {
                logger.error("webSocket断开了", e);
                throw e;
            } catch (Exception e) {
                logger.error("发送消息失败", e);
            }
        }
    }

    public static void sendBinary(Session session, byte[] data) {
        synchronized (session) {
            try {
                session.getBasicRemote().sendBinary(ByteBuffer.wrap(data));
            } catch (IOException e) {
                logger.error("发送消息失败",e);
            }
        }
    }
}
