package com.sjyt.icom.asst.context.handle.wsframe;

import com.google.gson.JsonSyntaxException;
import com.sjyt.icom.asst.common.enums.ErrorCodeEnum;
import com.sjyt.icom.asst.common.enums.MsgTypeEnum;
import com.sjyt.icom.asst.common.model.message.NewsLetter;
import com.sjyt.icom.asst.common.model.sdp.RespError;
import com.sjyt.icom.asst.common.util.FuncUtils;
import com.sjyt.icom.asst.common.util.JsonUtils;
import com.sjyt.icom.asst.context.handle.cmd.CmdHandleContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 创建连接之后，客户端发送的消息都会在这里处理
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/1 16:02
 */
@Slf4j
@Component
@AllArgsConstructor
public class TextWsFrameHandle extends WsFrameHandle {
    private final CmdHandleContext cmdHandleContext;
    /**
     * 执行链
     *
     * @param event t
     */
    @Override
    public void doChain(WsFrameEvent event) {
        WebSocketFrame frame = event.getFrame();
        ChannelHandlerContext ctx = event.getCtx();
        FuncUtils.isTrue(frame instanceof TextWebSocketFrame).trueHandle(() -> {
            assert frame instanceof TextWebSocketFrame;
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) frame;
            String text = textWebSocketFrame.text();
            log.info("收到来自客户端的消息");
            NewsLetter newsLetter = null;
            try {
                newsLetter = JsonUtils.jsonToPojo(text, NewsLetter.class);
            } catch (JsonSyntaxException e) {
                log.error(ErrorCodeEnum.REQ_PARAM_ERROR.getValue() + "{}", e.getMessage());
                RespError respError = RespError.builder().msgType(MsgTypeEnum.RespError.getCode()).msg(ErrorCodeEnum.REQ_PARAM_ERROR.getValue())
                        .code(ErrorCodeEnum.REQ_PARAM_ERROR.getCode()).build();
                ctx.writeAndFlush(new TextWebSocketFrame(JsonUtils.pojoToJson(respError)));
            }
            Optional.ofNullable(newsLetter).ifPresent(cmdHandleContext::todo);
        });
    }
}
