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

import android.util.Log;

import org.iotivity.OCRepresentation;
import org.iotivity.OCRequest;
import org.iotivity.OCRequestHandler;
import org.iotivity.OCStatus;
import org.iotivity.bridge.homeserver.BridgeService;
import org.iotivity.bridge.homeserver.model.Light;
import org.iotivity.bridge.homeserver.BridgeServerActivity;
import org.iotivity.oc.OcCborException;
import org.iotivity.oc.OcRepresentation;
import org.iotivity.oc.OcUtils;

public class PostLightRequestHandler implements OCRequestHandler {

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

    private BridgeService service;
    private Light light;

    public PostLightRequestHandler(BridgeService service, Light light) {
        this.service = service;
        this.light = light;
    }

    @Override
    public void handler(OCRequest request, int interfaces) {
        Log.d(TAG, "inside Post Light Request Handler");

        service.msg("Post "+request.getResource().getUri()+" Request Received.");

        OCRepresentation rep = request.getRequestPayload();
        while (rep != null) {
            if (Light.SWITCH_KEY.equalsIgnoreCase(rep.getName())) {
                light.setSwitchOn(rep.getValue().getBool());
                service.msg("\t\t" + Light.SWITCH_KEY + ": " + light.isSwitchOn());
            }

            if (Light.DIMMING_SETTING_KEY.equalsIgnoreCase(rep.getName())) {
                light.setDimmingLevel((int) rep.getValue().getInteger());
                service.msg("\t\t" + Light.DIMMING_SETTING_KEY + ": " + light.getDimmingLevel());
            }
            rep = rep.getNext();
        }

        service.printLine();
        OcUtils.sendResponse(request, OCStatus.OC_STATUS_CHANGED);
    }
}
