package com.ym.im.handler;

import com.ym.im.entity.ChatRecord;
import com.ym.im.entity.MsgBody;
import com.ym.im.exception.IMessageException;
import com.ym.im.service.MsgBodyService;
import com.ym.im.util.MessageUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;

/**
 * @author: JJww
 * 单聊
 * @Date:2019-05-17
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class SingleChatHandler extends BaseHandler<MsgBody<ChatRecord>> {

    @Autowired
    private MsgBodyService msgBodyService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgBody<ChatRecord> msgBody) throws Exception {

        try {
            msgBodyService.msgBodyHandle(ctx, msgBody);
        } catch (ConstraintViolationException e) {
            log.error(e.getMessage());
            ConstraintViolation<?> next;
            final ArrayList<String> errorMsg = new ArrayList<>();
            for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
                next = constraintViolation;
                errorMsg.add(next.getMessage() + " " + ((PathImpl) next.getPropertyPath()).getLeafNode().asString() + " = " + next.getInvalidValue());
            }
            msgBody.setStatus(MsgBody.ERROR);
            msgBody.setMessage(errorMsg.toString());
            ctx.channel().writeAndFlush(msgBody);
        } catch (IMessageException e) {
            msgBody.setStatus(MsgBody.ERROR);
            msgBody.setMessage(MessageUtils.getMsg(e.getI18nError()));
            ctx.channel().writeAndFlush(msgBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
