package org.iotivity.bridge.homeserver.handler.client;

import org.iotivity.OCClientResponse;
import org.iotivity.OCQos;
import org.iotivity.OCResponseHandler;
import org.iotivity.OCStatus;
import org.iotivity.bridge.homeserver.BridgeServerActivity;
import org.iotivity.bridge.homeserver.model.Light;
import org.iotivity.bridge.homeserver.utils.Utils;
import org.iotivity.oc.OcRemoteResource;
import org.iotivity.oc.OcUtils;

public class Post2LightResponseHandler implements OCResponseHandler {

    private static final String TAG = Post2LightResponseHandler.class.getSimpleName();

    private BridgeServerActivity activity;
    private Light light;
    private OcRemoteResource resource ;

    public Post2LightResponseHandler(BridgeServerActivity activity, OcRemoteResource resource, Light light) {
        this.activity = activity;
        this.light = light;
        this.resource = resource ;
    }

    @Override
    public void handler(OCClientResponse response) {

        activity.msg("POST2 "+resource.getUri()+" Response Handler: Code = "+response.getCode().toString());
        if(response.getCode() != OCStatus.OC_STATUS_CHANGED && response.getCode() != OCStatus.OC_STATUS_CREATED) {
            activity.showErrorDialog("POST2 "+resource.getUri()+" Response Handler Error",
                    "Result Code = " + response.getCode().toString());
            activity.printLine();
            return;
        }

        activity.printLine();
        activity.showResultDialog("POST2 "+resource.getUri()+" Response Handler Result",
                "Result Code = " + response.getCode().toString());


        // Observe the response of Post Request
        ObserveLightResponseHandler observerLight = new ObserveLightResponseHandler(activity, resource, light);
        OcUtils.doObserve(resource.getUri(), Utils.getCoapsEndpoint(resource.getEndpoints()), null, observerLight, OCQos.LOW_QOS);
        activity.msg("Sent OBSERVE request");
        activity.printLine();

        // Stop trigger register. It will be stop Observe after 30secs
        StopObserveTriggerHandler stopObserve = new StopObserveTriggerHandler(resource);
        OcUtils.setDelayedHandler(stopObserve, 10);
        activity.msg("Stop OBSERVE Trigger register");
        activity.printLine();

    }
}
