package com.tax.token.service.websocket;

import ch.qos.logback.classic.Logger;
import com.tax.token.constants.TokenConstants;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class NioWebSocketClient {

    protected Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());

    public  Channel channel = null;
    private String webSocketUrl = null;

    private Bootstrap boot;

    private EventLoopGroup group;

    public  boolean retryConnectFlag = false;

    public static void main(String[] args) throws Exception{
        NioWebSocketClient client = new NioWebSocketClient();
        WebSocketClientService.sendTaxNoForToken(client.getChannel(), "91110108339805094M");
//        WebSocketClientService.sendClientHelloForToken(client.getChannel(), "110101123456021","1100");
//        WebSocketClientService.connectClient(client.getChannel());
//        while (true) {
//            WebSocketClientService.sendClientHelloForToken(client.getChannel(), "91110108MA01856G4X","1100");
//            TimeUnit.SECONDS.sleep(10);
//        }
//        WebSocketClientService.sendDataForSign(client.getChannel(),"110101123456021","123");
//        TextWebSocketFrame frame = new TextWebSocketFrame("我是文本");
//        NioWebSocketClient.getChannel().writeAndFlush(frame);
        client.shutdown();
    }

    public NioWebSocketClient(){
        try {
            this.webSocketUrl = TokenConstants.WEB_SOCKET_URL;
            this.init();
            this.doConnect();
            //WebSocketClientService.connectClient(channel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init(){
//        group = new NioEventLoopGroup();
//        boot = new Bootstrap();
//        boot.option(ChannelOption.SO_KEEPALIVE,true)
//                .option(ChannelOption.TCP_NODELAY,true)
//                .option(ChannelOption.SO_BACKLOG,1024*1024*10)
//                .group(group)
//                .handler(new LoggingHandler(LogLevel.INFO))
//                .channel(NioSocketChannel.class)
//                .handler(new ChannelInitializer<SocketChannel>() {
//                    protected void initChannel(SocketChannel socketChannel) throws Exception {
//                        ChannelPipeline p = socketChannel.pipeline();
//                        p.addLast(new ChannelHandler[]{new HttpClientCodec(),
//                                new HttpObjectAggregator(1024*1024*10)});
//                        p.addLast("hookedHandler", new WebSocketClientHandler());
//                    }
//          });
    }


    public  void doConnect() throws Exception {
//        synchronized (boot) {
//            URI websocketURI = new URI(webSocketUrl);
//            HttpHeaders httpHeaders = new DefaultHttpHeaders();
//            //进行握手
//            WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(websocketURI, WebSocketVersion.V13, (String) null, true, httpHeaders);
//
//            boot.remoteAddress(websocketURI.getHost(), websocketURI.getPort());
//            ChannelFuture sync = boot.connect().addListener((ChannelFuture futureListener) -> {
//            final EventLoop eventLoop = futureListener.channel().eventLoop();
//            if (!futureListener.isSuccess()) {
//                logger.info("客户端与服务端建立连接失败，10s之后尝试重连...");
//                // 10s秒之后重连
//                eventLoop.schedule(() -> {
//                    try {
//                        doConnect();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }, 10, TimeUnit.SECONDS);
//            } else {
//                if (retryConnectFlag) {
//                    // 如果连接成功后，再次断开，则尝试重连。
//                    retryConnectFlag = false;
//                    logger.info("客户端重连成功");
//                    System.out.println(channel);
//                } else {
//                    // 客户端首次成功连接服务端后，这里有个验证登录服务端的动作（不要验证可以取消）
//                    logger.info("客户端与服务器连接成功，port：8888，开始登录服务端...");
//                }
//            }
//
//            });
//            channel = sync.sync().channel();
//
//            System.out.println("websocket connected");
//            System.out.println(channel);
//            WebSocketClientHandler handler = (WebSocketClientHandler) channel.pipeline().get("hookedHandler");
//            handler.setHandshaker(handshaker);
//            handshaker.handshake(channel);
//            //阻塞等待是否握手成功
//            handler.handshakeFuture().sync();
//            WebSocketClientService.connectClient(channel);
//        }

    }

    public  Channel getChannel(){
        return this.channel;
    }

    public void writeAndFlush(String text){
        TextWebSocketFrame frame = new TextWebSocketFrame(text);
        this.channel.writeAndFlush(frame);
    }

    public void shutdown(){
        try {
            channel.close().sync();
            group.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
