package it.integry.integrywmsnative.core.wifi;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;

import it.integry.integrywmsnative.core.REST.consumers.ISingleValueOperationCallback;

public class WiFiStatusChecker {


    public enum SIGNAL {
        EXCELLENT,
        GOOD,
        FAIR,
        WEAK,
        NONE
    }

    private ISingleValueOperationCallback<SIGNAL> mCallback;

    private WifiManager mWifiManager;
    private int mNumberOfLevels = 4;

    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) {
                WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), mNumberOfLevels);

                SIGNAL signal;

                switch (level){
                    case 0: signal = SIGNAL.WEAK; break;
                    case 1: signal = SIGNAL.FAIR; break;
                    case 2: signal = SIGNAL.GOOD; break;
                    case 3: signal = SIGNAL.EXCELLENT; break;
                    default: signal = SIGNAL.NONE; break;
                }

                mCallback.onResult(signal);

                handler.postDelayed(this, MILLIS_DELAY);
            }
        }
    };

    public WiFiStatusChecker(Context context){
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    }

    public void startMonitoring(ISingleValueOperationCallback<SIGNAL> callback){
        this.mCallback = callback;
        shouldExecute = true;

        handler.post(runnableCode);
    }

    public void stopMonitoring(){
        shouldExecute = false;
    }

}
