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.AbstractImCmdStrategy;
import com.wecloud.im.ws.strategy.ImCmdStrategyFactory;
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 WsDataReader {
    private static final Logger log = LoggerFactory.getLogger(WsDataReader.class);

    @Resource
    private ImCmdStrategyFactory receiveStrategyContext;

    @Resource
    private WriteDataService writeDataService;


    /**
     * 在此开始进入业务流程子线程，将不占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().asLongText());


        // 解析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());
        // 使用策略模式， 根据不同类型请求调用不同实现类
        AbstractImCmdStrategy cmdStrategy = receiveStrategyContext.getStrategy(wsRequestUriPathEnum);
        cmdStrategy.process(receiveModel, ctx, data, appKey, clientId);

    }

}
