package com.ym.im.handler;

import com.ym.im.entity.base.ChannelAttributeKey;
import com.ym.im.exception.HttpException;
import com.ym.im.factory.SingleChatFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: JJww
 * @Date:2019/11/14
 */
@Component
@ChannelHandler.Sharable
public abstract class BaseHandler<T> extends SimpleChannelInboundHandler<T> {

    @Autowired
    private SingleChatFactory singleChatFactory;

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        singleChatFactory.getService(ctx.channel().attr(ChannelAttributeKey.ROLE_TYPE).get()).offline(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof HttpException) {
            return;
        }
        singleChatFactory.getService(ctx.channel().attr(ChannelAttributeKey.ROLE_TYPE).get()).offline(ctx);
    }

}
