package com.gyee.edge.gateway.client;

import com.gyee.edge.gateway.message.GYMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.rxtx.RxtxChannel;
import io.netty.channel.rxtx.RxtxChannelConfig;
import io.netty.channel.rxtx.RxtxDeviceAddress;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;


public class IEC102SerialClient implements IClient {

    private EndPoint endPoint;

    private IEC102RxtxClientHandler defaultHandler;

    private EventLoopGroup eventLoop;

    private volatile Channel channel;

    private volatile boolean disconnected = false;
    private volatile boolean reconnect = false;


    private int status;

    public IEC102SerialClient(EndPoint endPoint1) {
        this.endPoint = endPoint1;
    }

    public EndPoint getEndPoint() {
        return endPoint;
    }

    @Override
    public Future<Integer> connect() {
        return null;
    }

    @Override
    public Future<Integer> reconnect() {
        return null;
    }

    @Override
    public void disconnect() {

    }

    @Override
    public boolean isConnected() {
        return false;
    }

    @Override
    public EventLoopGroup getEventLoop() {
        return null;
    }

    @Override
    public Future<Integer> sendMessage(GYMessage gyMessage) {
        return null;
    }

    @Override
    public Future<Integer> send(Byte[] bytes) {
        return null;
    }

    public int getStatus() {
        return status;
    }

    public void createRxtx(IEC102RxtxClientHandler handler, String portName) throws Exception {
        System.out.println(portName);
        //串口使用阻塞io
        EventLoopGroup group = new OioEventLoopGroup();
        try {
            Bootstrap bootstrap  = new Bootstrap();
            bootstrap.group(group)
                    .channelFactory(() -> {
                        RxtxChannel rxtxChannel = new RxtxChannel();
                        rxtxChannel.config()
                                .setBaudrate(9600)
                                .setDatabits(RxtxChannelConfig.Databits.DATABITS_8)
                                .setParitybit(RxtxChannelConfig.Paritybit.NONE)
                                .setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1);
                        return rxtxChannel ;
                    })
                    .handler(new ChannelInitializer<RxtxChannel>() {
                        @Override
                        protected void initChannel(RxtxChannel rxtxChannel) {
                            rxtxChannel.pipeline().addLast(
                                    new LineBasedFrameDecoder(60000),
                                    new StringEncoder(StandardCharsets.UTF_8),
                                    new StringDecoder(StandardCharsets.UTF_8),
                                    handler
                            );
                        }
                    });

            ChannelFuture f = bootstrap.connect(new RxtxDeviceAddress(portName)).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public void start() {

    }

    public void start(IEC102RxtxClientHandler handler, String portName){
        CompletableFuture.runAsync(()->{
            try {
                //阻塞的函数
                createRxtx(handler,portName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, Executors.newSingleThreadExecutor());//不传默认使用ForkJoinPool，都是守护线程
    }

    public void stop() {

    }

    public void restart() {

    }

}
