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.expansion.RunnableArgs;
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 RunnableArgs<Boolean> callback) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();

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

            try {
                Response response = client.newCall(request).execute();
                boolean status = response.isSuccessful();
                response.close();
                callback.run(status);
            } catch (IOException e) {
                callback.run(false);
            }

        }).start();
    }

}
