package it.integry.integrywmsnative.core.rest.watcher;

import android.os.Handler;

import java.util.ArrayList;
import java.util.List;

import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.utility.UtilityServer;
import it.integry.integrywmsnative.core.utility.UtilityString;

public class ServerStatusChecker {

    private static final ServerStatusChecker instance = new ServerStatusChecker();

    private final List<RunnableArgs<Boolean>> mCallback = new ArrayList<>();

    private final RunnableArgs<Boolean> mInternalCallback = value -> {
        for (RunnableArgs<Boolean> callback : mCallback) {
            callback.run(value);
        }
    };

    private boolean shouldExecute = true;
    private final long MILLIS_DELAY = 5 * 1000;


    private final Handler handler = new Handler();
    private final Runnable runnableCode = new Runnable() {
        @Override
        public void run() {
            if (shouldExecute && !UtilityString.isNullOrEmpty(SettingsManager.i().getServer().getHost())) {
                UtilityServer.isEmsApiAvailable(
                        SettingsManager.i().getServer().getHost(),
                        SettingsManager.i().getServer().getPort(),
                        () -> mInternalCallback.run(true),
                        ex -> mInternalCallback.run(false));
                handler.postDelayed(this, MILLIS_DELAY);
            }
        }
    };

    public void addCallback(RunnableArgs<Boolean> callback) {
        this.mCallback.add(callback);
    }

    public void removeCallback(RunnableArgs<Boolean> callback) {
        this.mCallback.remove(callback);
    }


    public static void init() {
        instance.shouldExecute = true;

        instance.handler.post(instance.runnableCode);
    }

    public static void dispose() {
        instance.shouldExecute = false;
    }

    public static ServerStatusChecker getInstance() {
        return instance;
    }

}
