package com.wecloud.im.ws.receive;

import com.fasterxml.jackson.databind.json.JsonMapper;
import com.wecloud.im.ws.enums.WsRequestCmdEnum;
import com.wecloud.im.ws.model.request.ReceiveModel;
import com.wecloud.im.ws.service.WriteDataService;
import com.wecloud.im.ws.strategy.AbstractReceiveStrategy;
import com.wecloud.im.ws.strategy.ReceiveStrategyContext;
import io.geekidea.springbootplus.framework.common.exception.BusinessException;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description ws 数据接收 转换类
 * @Author hewei hwei1233@163.com
 * @Date 2019-12-03
 */
@Service
public class ReadWsData {
    private static final Logger log = LoggerFactory.getLogger(ReadWsData.class);

    // idea此处报红 属于正常
//    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Resource
    private ReceiveStrategyContext receiveStrategyContext;

    @Resource
    private WriteDataService writeDataService;

    private static final String PING = "ping";

    /**
     * 在此开始进入业务流程子线程，将不占netty的io线程
     *
     * @param data
     * @throws Exception
     */
    public void convertModel(String data, ChannelHandlerContext ctx, String appKey, String clientId) throws Exception {

        log.info("appWS收到data:" + data + "\nappKey+clientId:" + appKey + ":" + clientId +
                ",channelId:" + ctx.channel().id().asShortText());
        if (PING.equals(data)) {
            log.info("收到心跳clientId:" + clientId);
            return;
        }

        // 解析json
        JsonMapper jsonMapper = new JsonMapper();
        ReceiveModel receiveModel = jsonMapper.readValue(data, ReceiveModel.class);
        if (null == receiveModel || null == receiveModel.getCmd()) {
            throw new BusinessException("null == receiveModel || null == receiveModel.getCmd()");
        }

        WsRequestCmdEnum wsRequestUriPathEnum = WsRequestCmdEnum.getByCode(receiveModel.getCmd());
        // 使用策略模式， 根据不同类型请求调用不同实现类
        AbstractReceiveStrategy receiveStrategy = receiveStrategyContext.getStrategy(wsRequestUriPathEnum);
        receiveStrategy.process(receiveModel, ctx, data, appKey, clientId);

    }

}
