package com.wecloud.dispatch.general;

import com.wecloud.dispatch.common.RequestVO;
import com.wecloud.dispatch.extend.ActionMessage;
import com.wecloud.dispatch.extend.ArgumentBox;
import com.wecloud.dispatch.extend.impl.DefaultArgumentBox;
import com.wecloud.dispatch.general.config.GeneralActionDispatcher;
import com.wecloud.dispatch.general.extend.ActionMessageResolver;
import com.wecloud.im.ws.sender.ChannelSender;
import com.wecloud.utils.JsonUtils;
import io.geekidea.springbootplus.framework.common.exception.BusinessException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author lixiaozhong
 */
@Component
@Slf4j
public class GeneralMessageHandler {

	@Autowired
	private GeneralActionDispatcher generalActionDispatcher;
	@Autowired
	private ActionMessageResolver actionMessageResolver;
	@Autowired
	private ChannelSender channelSender;

	public void doMessage(Long senderClientId, ChannelHandlerContext ctx, String data) {
		if(log.isDebugEnabled()) {
			log.debug("appWS收到data: {}\n senderClientId:{}, channelId:{}", data, senderClientId, ctx.channel().id().asLongText());
		}
		// 解析jsonO
		RequestVO requestVO = JsonUtils.decodeJson(data, RequestVO.class);


		if (null == requestVO || null == requestVO.getAction()) {
			throw new BusinessException("null == requestVO || null == requestVO.getAction()");
		}

		ActionMessage am = actionMessageResolver.resolver(generalActionDispatcher, requestVO);
		Object res = generalActionDispatcher.action(am);
		channelSender.sendMsgLocal((NioSocketChannel)ctx.channel(), res);
	}

	public ArgumentBox getArgumentBox() {
		ArgumentBox beanBox = new DefaultArgumentBox();
		return beanBox;
	}
}
