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

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

import org.iotivity.OCClientResponse;
import org.iotivity.OCRep;
import org.iotivity.OCRepresentation;
import org.iotivity.OCResponseHandler;
import org.iotivity.OCStatus;
import org.iotivity.bridge.homeserver.BridgeService;
import org.iotivity.bridge.homeserver.utils.Utils;
import org.iotivity.oc.OcRemoteResource;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class ObserveResponseHandler implements OCResponseHandler {

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

    private BridgeService service;
    private OcRemoteResource resource ;
    private BridgeService.ResponseType res_type = BridgeService.ResponseType.OBSERVE ;

    public ObserveResponseHandler(BridgeService service, OcRemoteResource resource) {
        this.service = service;
        this.resource = resource;
    }

    public ObserveResponseHandler(BridgeService service, OcRemoteResource resource, BridgeService.ResponseType res_type) {
        this.service = service;
        this.resource = resource;
        this.res_type = res_type;
    }

    @Override
    public void handler(OCClientResponse response) {

        Log.d(TAG, "OBSERVE "+resource.getUri()+" Response Handler: Code = "+response.getCode().toString());
        if(response.getCode() != OCStatus.OC_STATUS_OK) {
            return;
        }

        OCRepresentation rep = response.getPayload();
        String json = OCRep.toJSON(rep, false); // boolean : prettyPrint or not
        Log.d(TAG, "OBSERVE "+resource.getUri()+" Response : " + json);

        try {
            JSONObject props = new JSONObject(json);
            JSONObject result = new JSONObject();
            result.put("id", resource.getAnchor() + resource.getUri());
            result.put("di", Utils.getDIFromAnchor(resource.getAnchor()));
            result.put("uri", resource.getUri());
            result.put("res_type", res_type.name());
            result.put("res_data", props);

            String result_str = result.toString().replace("\\", "");
            service.broadcastResult(BridgeService.ResultType.OK.ordinal(), result_str);

        } catch (JSONException ex) {
            Log.e(TAG, "JSON Error : ", ex);
        }
    }
}
