package com.hmsoft.remote.rmi.rpc;

import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import org.apache.log4j.Logger;
import com.hmsoft.remote.rmi.codec.Codec;
import com.hmsoft.remote.rmi.codec.NettyCodecAdapter;
import com.hmsoft.remote.rmi.codec.TransCodec;
import com.hmsoft.remote.rmi.common.utils.NetUtils;
import com.hmsoft.remote.rmi.exception.RemotingException;
import com.hmsoft.remote.rmi.handler.ExchangeHandler;
import com.hmsoft.remote.rmi.handler.HeaderExchangeHandler;
import com.hmsoft.remote.rmi.transport.NettyChannel;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

/**
 * 
 * @author zq
 *
 */
public class NettyServer extends AbstractServer {

	private static final Logger logger = Logger.getLogger(NettyServer.class);
	
	private ServerBootstrap bootstrap;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private io.netty.channel.Channel channel;
    private Map<String, NettyChannel> channels; // <ip:port, channel>
    
    public NettyServer(String url, ExchangeHandler handler) throws RemotingException {
    	super(url, new HeaderExchangeHandler(handler));
    }
	
    @Override
	protected void doOpen() throws Throwable {
		bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
        workerGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerWorker", true));
        
        final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
        channels = nettyServerHandler.getChannels();
        
        bootstrap.group(bossGroup, workerGroup)
		        .channel(NioServerSocketChannel.class)
		        .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
		        .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
		        .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
		        .childHandler(new ChannelInitializer<NioSocketChannel>() {
			            @Override
			            protected void initChannel(NioSocketChannel ch) throws Exception {
			            	final Codec codec = new TransCodec();
			            	NettyCodecAdapter adapter = new NettyCodecAdapter(codec, codec, getUrl(), NettyServer.this);
	                        ch.pipeline()
	                        		.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
		                            .addLast("decoder", adapter.getDecoder())
		                            .addLast("encoder", adapter.getEncoder())
		                            .addLast("handler", nettyServerHandler);
			            }
			    });
		// bind
		ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
		channelFuture.syncUninterruptibly();
		channel = channelFuture.channel();
	}
	
    @Override
    protected void doClose() throws Throwable {
        try {
            if (channel != null) {
                // unbind.
                channel.close();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
        try {
            Collection<NettyChannel> channels = getChannels();
            if (channels != null && channels.size() > 0) {
                for (NettyChannel channel : channels) {
                    try {
                        channel.close();
                    } catch (Throwable e) {
                        logger.warn(e.getMessage(), e);
                    }
                }
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
        try {
            if (bootstrap != null) {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
        try {
            if (channels != null) {
                channels.clear();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
    }
    
    public Collection<NettyChannel> getChannels() {
        Collection<NettyChannel> chs = new HashSet<NettyChannel>();
        for (NettyChannel channel : this.channels.values()) {
            if (channel.isConnected()) {
                chs.add(channel);
            } else {
                channels.remove(NetUtils.toAddressString(channel.getRemoteAddress()));
            }
        }
        return chs;
    }
    
    public NettyChannel getChannel(InetSocketAddress remoteAddress) {
        return channels.get(NetUtils.toAddressString(remoteAddress));
    }
    
    public Map<String, NettyChannel> getChannelsMap() {
    	return channels;
    }
    
    public void send(Object message, boolean sent) throws RemotingException {
        Collection<NettyChannel> channels = getChannels();
        for (NettyChannel channel : channels) {
            if (channel.isConnected()) {
                channel.send(message, sent);
            }
        }
    }
}
