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

import android.util.Log;
import android.util.Pair;

import org.iotivity.OCClientResponse;
import org.iotivity.OCInterfaceMask;
import org.iotivity.OCResponseHandler;
import org.iotivity.OCStatus;
import org.iotivity.bridge.homeserver.BridgeServerActivity;
import org.iotivity.bridge.homeserver.utils.Utils;
import org.iotivity.oc.OcRemoteResource;

import java.util.ArrayList;

public class GetCommonResponseHandler implements OCResponseHandler {

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

    private BridgeServerActivity activity;
    private OcRemoteResource resource ;

    public GetCommonResponseHandler(BridgeServerActivity activity, OcRemoteResource resource) {
        this.activity = activity ;
        this.resource = resource ;
    }

    @Override
    public void handler(OCClientResponse response) {
        activity.msg("Get "+resource.getUri()+" Response Handler: Code = "+response.getCode().toString());
        if(response.getCode() != OCStatus.OC_STATUS_OK) {
            activity.showErrorDialog("Get "+resource.getUri()+" Response Handler Error",
                    "Result Code = " + response.getCode().toString());
            activity.printLine();
            return;
        }

        final ArrayList<Pair<String, Object>> props = ResponseParsingHelper.parseClientResponse(response, activity);

        if((resource.getInterfaceMask() & OCInterfaceMask.RW) > 0 ||
                (resource.getInterfaceMask() & OCInterfaceMask.A) > 0) {
            activity.showPropertiesDialog( "Properties of " + this.resource.getUri(), props, resource);
            Log.d(TAG, "Properties : " + Utils.propertiesToString(props));
        } else {
            activity.showResultDialog("Get " + resource.getUri() + " Response Handler Result",
                    "Result Code = " + response.getCode().toString() +"\n\n"+ Utils.propertiesToString(props));
            Log.d(TAG, "Properties : " + Utils.propertiesToString(props));
        }
    }
}
