package com.wecloud.dispatch.general;

import com.wecloud.dispatch.common.BaseRequest;
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
		BaseRequest baseRequest = JsonUtils.decodeJson(data, BaseRequest.class);


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

		ActionMessage am = actionMessageResolver.resolver(generalActionDispatcher, baseRequest);
		am.setSenderChannel(ctx.channel());
		am.setSenderClientId(senderClientId);
		Object res = generalActionDispatcher.action(am);
		channelSender.sendMsgLocal((NioSocketChannel)am.getSenderChannel(), res);
	}

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