package com.hmsoft.remote.rmi.handler;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;

import com.hmsoft.remote.rmi.transport.NettyChannel;

/**
 * 
 * @author zq
 *
 */
public class ChannelHandlerDispatcher implements ChannelHandler {


    private final Collection<ChannelHandler> channelHandlers = new CopyOnWriteArraySet<ChannelHandler>();

    public ChannelHandlerDispatcher() {
    }

    public ChannelHandlerDispatcher(ChannelHandler... handlers) {
        this(handlers == null ? null : Arrays.asList(handlers));
    }

    public ChannelHandlerDispatcher(Collection<ChannelHandler> handlers) {
        if (handlers != null && !handlers.isEmpty()) {
            this.channelHandlers.addAll(handlers);
        }
    }

    public Collection<ChannelHandler> getChannelHandlers() {
        return channelHandlers;
    }

    public ChannelHandlerDispatcher addChannelHandler(ChannelHandler handler) {
        this.channelHandlers.add(handler);
        return this;
    }

    public ChannelHandlerDispatcher removeChannelHandler(ChannelHandler handler) {
        this.channelHandlers.remove(handler);
        return this;
    }

    @Override
    public void connected(NettyChannel channel) {
        for (ChannelHandler listener : channelHandlers) {
            try {
                listener.connected(channel);
            } catch (Throwable t) {
                //logger.error(t.getMessage(), t);
            	t.printStackTrace();
            }
        }
    }

    @Override
    public void disconnected(NettyChannel channel) {
        for (ChannelHandler listener : channelHandlers) {
            try {
                listener.disconnected(channel);
            } catch (Throwable t) {
                //logger.error(t.getMessage(), t);
            	t.printStackTrace();
            }
        }
    }

    @Override
    public void sent(NettyChannel channel, Object message) {
        for (ChannelHandler listener : channelHandlers) {
            try {
                listener.sent(channel, message);
            } catch (Throwable t) {
                //logger.error(t.getMessage(), t);
            	t.printStackTrace();
            }
        }
    }

    @Override
    public void received(NettyChannel channel, Object message) {
        for (ChannelHandler listener : channelHandlers) {
            try {
                listener.received(channel, message);
            } catch (Throwable t) {
                //logger.error(t.getMessage(), t);
            	t.printStackTrace();
            }
        }
    }

    @Override
    public void caught(NettyChannel channel, Throwable exception) {
        for (ChannelHandler listener : channelHandlers) {
            try {
                listener.caught(channel, exception);
            } catch (Throwable t) {
                //logger.error(t.getMessage(), t);
            	t.printStackTrace();
            }
        }
    }
}
