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

import android.util.Log;

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

public class PostBridgeRequestHandler implements OCRequestHandler {

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

    private BridgeServerActivity activity;
    private Bridge bridge;

    public PostBridgeRequestHandler(BridgeServerActivity activity, Bridge bridge) {
        this.activity = activity;
        this.bridge = bridge;
    }

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

        activity.msg("Post Bridge:" + request.getResource().getUri());

        if(request.getResource().getUri().equals(Bridge.SECUREMODE_URI)) {

            OcRepresentation rep = new OcRepresentation(request.getRequestPayload());
            while (rep != null) {
                try {
                    if (Bridge.SECUREMODE_RESOURCE_NAME.equalsIgnoreCase(rep.getKey())) {
                        bridge.setSecureMode(rep.getBoolean(Bridge.SECUREMODE_RESOURCE_NAME));
                        activity.msg("\t\t" + Bridge.SECUREMODE_RESOURCE_NAME + ": " + bridge.isSecureMode());
                    }
                } catch (OcCborException e) {
                    // ignore -- no switch value
                }
                rep = rep.getNext();
            }
        }
        activity.printLine();
        OcUtils.sendResponse(request, OCStatus.OC_STATUS_CHANGED);
    }
}
