package com.signal.sig.comm;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class SigCommClientHandler extends ChannelInitializer<SocketChannel> {
	
	ChannelFuture cf = null;
    EventLoopGroup group = null;
    
    public void connect(String host, int port) throws Exception {
    	
    	group = new NioEventLoopGroup();

		Bootstrap b = new Bootstrap();
		b.group(group)
		.channel(NioSocketChannel.class)
		.option(ChannelOption.TCP_NODELAY, true)
		.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				ChannelPipeline cp = sc.pipeline();
				cp.addLast(new SigCommDecoder());
			}
		});

		try {
   			cf = b.connect(host, port).sync();
   			System.out.println("b.connect() 후");
   			
   			//cf.channel().closeFuture().syncUninterruptibly().wait();
   			//System.out.println("cf.channel()  후");
			cf.channel().closeFuture().sync();

   		} catch(Exception e) {
   			System.out.println("[ DBUG ]================connection Exception================");
   			System.out.println("[ DBUG ]hots : " + host + " / port : " + port);
   			e.printStackTrace();
   			//this.connect(host, port);
   			Thread.sleep(5000);
   			SigCommThread.start();

   		} finally {
   			//group.shutdownGracefully();
   		}
   	}

    public void close() {
        cf.channel().close();
        group.shutdownGracefully();
    }

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
