package com.cm.websocket.handler;

import com.alibaba.fastjson.JSONObject;
import com.cm.websocket.WebSocket;
import com.cm.websocket.enums.AppSocketTypeEnum;
import com.cm.websocket.enums.SendStatusEnum;
import com.cm.websocket.pojo.AppSocketMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.SendHandler;
import javax.websocket.SendResult;
import javax.websocket.Session;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: TextSendHandler
 * @Description: 文本发送处理器
 * @Author: wanggeng
 * @Date: 2021/1/14 12:39 下午
 * @Version: 1.0
 */
public class TextSendHandler implements SendHandler {
    private static final Logger LOG = LoggerFactory.getLogger(TextSendHandler.class);

    private Session fromSession;
    private AppSocketMessage appSocketMessage;

    public TextSendHandler() {
    }

    public TextSendHandler(Session fromSession, AppSocketMessage appSocketMessage) {
        this.fromSession = fromSession;
        this.appSocketMessage = appSocketMessage;
    }

    @Override
    public void onResult(SendResult sendResult) {
        if (fromSession == null || appSocketMessage == null) {
            return;
        }
        if (sendResult.isOK()) {
            appSocketMessage.setType(AppSocketTypeEnum.SEND_STATUS.getValue());
            appSocketMessage.setBody(JSONObject.toJSONString(new AppSocketMessage.SendStatusBody(SendStatusEnum.SUCCESS.getValue(), SendStatusEnum.SUCCESS, "OK")));
            WebSocket.send(fromSession, appSocketMessage);
        } else {
            LOG.error(sendResult.getException().getMessage(), sendResult.getException().getMessage());
        }

    }

}
