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

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

import org.iotivity.OCClientResponse;
import org.iotivity.OCRepresentation;
import org.iotivity.OCResponseHandler;
import org.iotivity.OCStatus;
import org.iotivity.OCUuidUtil;
import org.iotivity.bridge.homeserver.BridgeService;
import org.iotivity.bridge.homeserver.utils.Utils;
import org.iotivity.oc.OcRemoteDevice;
import org.iotivity.oc.OcRemoteResource;

import java.util.ArrayList;

public class GetDeviceSecuredResponseHandler implements OCResponseHandler {

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

    private BridgeService service ;
    private OcRemoteDevice device ;
    private OcRemoteResource resource ;

    public GetDeviceSecuredResponseHandler(BridgeService service, OcRemoteDevice device, OcRemoteResource resource) {
        this.service = service ;
        this.device = device ;
        this.resource = resource ;
    }

    @Override
    public void handler(OCClientResponse response) {

        service.msg("Get "+resource.getUri()+" of "+device.getName()+" Response Handler: Code = "+response.getCode().toString());
        if(response.getCode() != OCStatus.OC_STATUS_OK) {
            service.msg("Get "+resource.getUri()+" Response Handler Error");
            service.printLine();
            return;
        }

        Log.d(TAG, "Remote Device Access Check Handler is STATUS_OK: " + OCUuidUtil.uuidToString(device.getDeviceId()) + ", " + device.getName());

        final ArrayList<Pair<String, Object>> props = new ArrayList<>();
        OCRepresentation rep = response.getPayload();
        while (rep != null) {
            switch (rep.getType()) {
                case OC_REP_BOOL:
                    service.msg("\t" + rep.getName() + " = " + rep.getValue().getBool());
                    props.add(new Pair(rep.getName(), rep.getValue().getBool()));
                    break;
                case OC_REP_INT:
                    service.msg("\t" + rep.getName() + " = " + rep.getValue().getInteger());
                    props.add(new Pair(rep.getName(), rep.getValue().getInteger()));
                    break;
                case OC_REP_STRING:
                    service.msg("\t" + rep.getName() + " = " + rep.getValue().getString());
                    props.add(new Pair(rep.getName(), rep.getValue().getString()));
                    break;
                case OC_REP_DOUBLE:
                    service.msg("\t" + rep.getName() + " = " + rep.getValue().getDouble());
                    props.add(new Pair(rep.getName(), rep.getValue().getDouble()));
                    break;
                default:
                    break;
            }
            rep = rep.getNext();
        }
        service.printLine();
        Log.d(TAG, "Properties : " + Utils.propertiesToString(props));

        service.addPairwisedDevice(device);

    }
}
