package jnet.client.network;

import io.netty.bootstrap.Bootstrap;
import jnet.client.Client;
import jnet.client.ClientMessageParser;
import jnet.client.gui.Tray;
import jnet.client.gui.Window;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import java.util.concurrent.TimeUnit;
import jnet.lib.LogFile;
import jnet.lib.Message;

public class NettyClient implements Runnable {

    private final String host;
    private final int port;
    private final Bootstrap bootstrap;
    private final EventLoopGroup group;
    static private Channel channel;
    
    private static boolean autoReconnectEnable;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        configureBootstrap();
    }

    private void configureBootstrap() {
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast("decoder", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader())));
                        ch.pipeline().addLast("encoder", new ObjectEncoder());
                        ch.pipeline().addLast("handler", new ClientHandler());
                    }
                });
    }

    @Override
    public void run() {
        try {
            connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void connect() {
        autoReconnectEnable = true;
        bootstrap.connect(host, port).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                channel = future.channel();
                System.out.println("Pripojeno k serveru " + host + ":" + port);
                Window.setConectionStatus("Připojeno");
            } else {
                LogFile.printErr("Pripojeni selhalo: " + future.cause().getMessage());
                reconnect();
            }
        });
    }

    public void reconnect() {
        if (autoReconnectEnable) {
            group.schedule(() -> {
                LogFile.printErr("Zkousim se znovu pripojit...");
                Window.setConectionStatus("Připojování ...");
                connect();
            }, 5, TimeUnit.SECONDS);
        }
        
    }

    public static void send(int type, Object obj) {
        channel.writeAndFlush(new Message(type, obj));
        LogFile.printDebug("<- Message type: " + type);
    }

    public static boolean isConnected() {
        if (channel != null && channel.isActive()) {
            return true;
        }
        return false;
    }

    public static void disconnect() {
        // vypne automaticke pripojeni
        autoReconnectEnable = false;
        // odpojí
        channel.disconnect();
        channel.close();
        // vypise do okna informaci
        Window.setConectionStatus("Odpojeno");
        // zmeni tray icon
        Tray.setStatusDisconnected();
        // zapíše do logu
        LogFile.printInfo("User disconnect");
    }

    public void shutdown() {
        group.shutdownGracefully();
    }

    public class ClientHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            if (msg instanceof Message) {
                Message m = (Message) msg;
                ClientMessageParser.parse((Message) msg);
            }
            if (msg instanceof String) {
                System.out.println("Server message: " + msg);
            }
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            LogFile.printErr("Spojeni bylo ukonceno");
            reconnect();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            System.err.println("Client error: " + cause);
            ctx.close();
            Client.connected = false;
        }

    }

}
