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

import android.os.Handler;

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

import it.integry.integrywmsnative.core.REST.consumers.ISingleValueOperationCallback;
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 ServerStatusChecker istance = new ServerStatusChecker();

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

    private ISingleValueOperationCallback<Boolean> mInternalCallback = value -> {
        for (ISingleValueOperationCallback callback : mCallback) {
            callback.onResult(value);
        }
    };

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


    private Handler handler = new Handler();
    private Runnable runnableCode = new Runnable() {
        @Override
        public void run() {
            if(shouldExecute && !UtilityString.isNullOrEmpty(SettingsManager.i().server.host)) {
                UtilityServer.isHostReachable(SettingsManager.i().server.host, SettingsManager.i().server.port, mInternalCallback);
                handler.postDelayed(this, MILLIS_DELAY);
            }
        }
    };

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

    }

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


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

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

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

    public static ServerStatusChecker getIstance() {
        return istance;
    }

}
