package com.mx.cneeds.server.wechat.common.dispatcher;

import com.alibaba.fastjson.JSON;
import com.mx.cneeds.server.wechat.common.codec.Invocation;
import com.mx.cneeds.server.wechat.common.json.WechatJsonMessage;
import com.mx.cneeds.server.wechat.websocket.config.NettyChannelManager;
import com.mx.cneeds.server.wechat.websocket.message.pojo.wechat.WechatMessageRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class MessageDispatcher {

    @Autowired
    private MessageHandlerContainer messageHandlerContainer;


    public void doWechatDispatcher(WechatJsonMessage jsonMessage){
        WechatMessageRequest wechatMessageRequest = new WechatMessageRequest();
        BeanUtils.copyProperties(jsonMessage,wechatMessageRequest);

        WechatMessageRequest.DataBean requestDataBean = new WechatMessageRequest.DataBean();
        BeanUtils.copyProperties(jsonMessage.getData(),requestDataBean);
        wechatMessageRequest.setData(requestDataBean);

        Invocation invocation = new Invocation(WechatMessageRequest.TYPE,wechatMessageRequest);
        sendToWechat(invocation);
    }

    private void sendToWechat(Invocation invocation) {
        // 获得 type 对应的 MessageHandler 处理器
        MessageHandler messageHandler = messageHandlerContainer.getMessageHandler(invocation.getType());
        // 获得  MessageHandler 处理器 的消息类
        Class<? extends Message> messageClass = MessageHandlerContainer.getMessageClass(messageHandler);
        // 解析消息
        Message message = JSON.parseObject(invocation.getMessage(), messageClass);
        // 执行逻辑
        // noinspection unchecked
        messageHandler.execute(null, message);
    }

}
