package it.integry.integrywmsnative.core.utility;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import it.integry.integrywmsnative.core.exception.InvalidLicenseException;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.gest.login.exception.ServerNotReachableException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UtilityServer {

    public static void isHostReachable(final String serverAddress, final int serverTCPport, final RunnableArgs<Boolean> callback) {
        new Thread(() -> {

            boolean connected = false;
            Socket socket;
            try {
                socket = new Socket();
                SocketAddress socketAddress = new InetSocketAddress(serverAddress, serverTCPport);
                socket.connect(socketAddress, 10000);
                if (socket.isConnected()) {
                    connected = true;
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                socket = null;
            }

            callback.run(connected);

        }).start();
    }

    public static void isEmsApiAvailable(final String serverAddress, final int serverTCPport, final Runnable onComplete, final RunnableArgs<Exception> onFailed) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(String.format("http://%s:%d/ems-api/system/ok", serverAddress, serverTCPport))
                    .build();

            try {
                Response response = client.newCall(request).execute();
                response.close();

                if (response.code() == 200) onComplete.run();
                else if (response.code() == 404)
                    onFailed.run(new ServerNotReachableException(serverAddress, serverTCPport, null));
                else if (response.code() == 550)
                    onFailed.run(new InvalidLicenseException());
                else onFailed.run(new Exception("Errore non identificato (STATUS: " + response.code() + ")"));
            } catch (IOException e) {
                onFailed.run(new ServerNotReachableException(serverAddress, serverTCPport, e));
            }

        }).start();
    }

}
