package com.wytehat.btlogger;

public class RangeStateMachine {
    public static final String HOT = "HOT";
    public static final String WARM = "WARM";
    public static final String COLD = "COLD";
    public static final String LOST = "LOST";
    private String state = LOST;
    private String candidate = LOST;
    private int candidateCount;

    public synchronized String update(double rssi) {
        String next;
        if (HOT.equals(state)) next = rssi < -65 ? WARM : HOT;
        else if (COLD.equals(state)) next = rssi > -75 ? WARM : COLD;
        else if (rssi > -60) next = HOT;
        else if (rssi < -80) next = COLD;
        else next = WARM;

        if (next.equals(state)) {
            candidate = next;
            candidateCount = 0;
        } else if (next.equals(candidate)) {
            candidateCount++;
            if (candidateCount >= 3) {
                state = next;
                candidateCount = 0;
            }
        } else {
            candidate = next;
            candidateCount = 1;
        }
        return state;
    }

    public synchronized void signalLost() {
        state = LOST;
        candidate = LOST;
        candidateCount = 0;
    }

    public synchronized String getState() { return state; }
}
