package com.wecloud.im.tillo.app_ws.receive;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.wecloud.im.tillo.app_ws.enums.WsRequestCmdEnum;
import com.wecloud.im.tillo.app_ws.model.request.ReceiveModel;
import com.wecloud.im.tillo.app_ws.service.MangerChannelService;
import com.wecloud.im.tillo.app_ws.service.WriteDataService;
import com.wecloud.im.tillo.app_ws.strategy.AbstractReceiveStrategy;
import com.wecloud.im.tillo.app_ws.strategy.ReceiveStrategyContext;
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 = ctx.channel().attr(MangerChannelService.APP_KEY).get();
        String clientId = ctx.channel().attr(MangerChannelService.CLIENT_ID).get();

        if (PING.equals(data)) {
            log.debug("收到心跳：" + clientId);
            return;
        }

        String language = ctx.channel().attr(MangerChannelService.LANGUAGE).get();


//        ReceiveModel requestModel = JSON.parseObject(data, ReceiveModel.class);

        JsonMapper jsonMapper = new JsonMapper();

        ReceiveModel receiveModel = null;
        try {
            receiveModel = jsonMapper.readValue(data, ReceiveModel.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (null == receiveModel || null == receiveModel.getCmd()) {
            return;
        }

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

        } catch (Exception e) {
            log.error("系统繁忙:" + data + ",appKey:" + appKey + ",clientId:" + clientId, e);
//            writeDataService.nullDataSuccess(requestModel, ResultStatus.SYS_BUSY, userId, language);
        }

    }


}
