package com.hmsoft.remote.rmi.rpc;

import com.hmsoft.remote.rmi.exception.RemotingException;
import com.hmsoft.remote.rmi.handler.ChannelHandler;
import com.hmsoft.remote.rmi.transport.NettyChannel;

/**
 * 服务端、客户端收到消息入口,再转发到handler处理.
 * @author zq
 *
 */
public class AbstractPeer implements ChannelHandler {

    private final ChannelHandler handler;
    private volatile String url;
    // closing closed means the process is being closed and close is finished
    private volatile boolean closing;
    private volatile boolean closed;
    
    public AbstractPeer(String url, ChannelHandler handler) {
        if (url == null) {
            throw new IllegalArgumentException("url == null");
        }
        if (handler == null) {
            throw new IllegalArgumentException("handler == null");
        }
        this.url = url;
        this.handler = handler;
    }
    
    public String getUrl() {
        return this.url;
    }
    
    public ChannelHandler getChannelHandler() {
    	return this.handler;
    }
    
    public void close() {
        this.closed = true;
    }
    
    public void close(int timeout) {
        close();
    }
    
    public void startClose() {
        if (isClosed()) {
            return;
        }
        this.closing = true;
    }
    
    public boolean isClosed() {
        return this.closed;
    }

    public boolean isClosing() {
        return this.closing && !this.closed;
    }
    
    @Override
    public void connected(NettyChannel ch) throws RemotingException {
        if (this.closed) {
            return;
        }
        this.handler.connected(ch);
    }

    @Override
    public void disconnected(NettyChannel ch) throws RemotingException {
    	this.handler.disconnected(ch);
    }

    @Override
    public void sent(NettyChannel ch, Object msg) throws RemotingException {
        if (this.closed) {
            return;
        }
        this.handler.sent(ch, msg);
    }

    @Override
    public void received(NettyChannel ch, Object msg) throws RemotingException {
        if (this.closed) {
            return;
        }
        this.handler.received(ch, msg);
    }

    @Override
    public void caught(NettyChannel ch, Throwable ex) throws RemotingException {
    	this.handler.caught(ch, ex);
    }
}
