import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapHandler;
import org.eclipse.californium.core.CoapResponse;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        var light_client = new CoapClient("coap://localhost:5683/light");
        var lamp_client = new CoapClient("coap://localhost:5683/light/lamp");
        while (true) {
            var relation = light_client.observe(new LampUpdateHandler(lamp_client));
            relation.wait();
        }
    }
}

class LampUpdateHandler implements CoapHandler {
    static String ON = "On";
    static String OFF = "Off";

    CoapClient lamp_client;
    public LampUpdateHandler(CoapClient lamp_client_) {
        lamp_client = lamp_client_;
    }

    @Override
    public void onLoad(CoapResponse coapResponse) {
        var content = coapResponse.getResponseText();
        var level = Integer.parseInt(content);
        System.out.println("Light at " + level);
        var state = OFF;
        if (level < 5) state = ON;
        System.out.println("Sending state " + state);
    }

    @Override
    public void onError() {
        System.err.println("Owno :s");
    }
}
