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

import android.util.Log;

import org.iotivity.OCQos;
import org.iotivity.OCUuid;
import org.iotivity.OCUuidUtil;
import org.iotivity.bridge.homeserver.BridgeServerActivity;
import org.iotivity.bridge.homeserver.BridgeService;
import org.iotivity.bridge.homeserver.utils.Utils;
import org.iotivity.oc.OcDeviceDiscoveryHandler;
import org.iotivity.oc.OcRemoteDevice;
import org.iotivity.oc.OcRemoteResource;
import org.iotivity.oc.OcUtils;

public class DeviceDiscoveryHandler implements OcDeviceDiscoveryHandler {

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

    private BridgeService service;
    private OCUuid self_di  ;

    public DeviceDiscoveryHandler(BridgeService service, OCUuid self_di) {
        this.service = service;
        this.self_di = self_di ;
    }

    @Override
    public void discoveredDevice(OcRemoteDevice remoteDevice) {
        Log.d(TAG, "Remote Device Discovery Handler: " + OCUuidUtil.uuidToString(remoteDevice.getDeviceId()) + ", " + remoteDevice.getName());

        /* Only pairwised devices except Bridge itself and OBT will be added in the pairwised device list */
        if(!OCUuidUtil.isEqual(remoteDevice.getDeviceId(), self_di) && !Utils.isObt(remoteDevice)) {

            /* check if Bridge has the discovered device's pairwised credential */
            if(service.hasPairwisedDeviceUUIDs(remoteDevice.getDeviceId())) {
                service.addPairwisedDevice(remoteDevice);
                //Log.d(TAG, "getAllResources : " + service.getDeviceResources(OCUuidUtil.uuidToString(remoteDevice.getDeviceId())));

                //Log.d(TAG, "getDeviceSpecificResources: " + service.doGetDeviceSpecificResources(OCUuidUtil.uuidToString(remoteDevice.getDeviceId())));
                //Log.d(TAG, "StopObserveAll : " + service.stopObserveDeviceSpecificResources(OCUuidUtil.uuidToString(remoteDevice.getDeviceId())));
                Log.d(TAG, "ObserveAll : " + service.doObserveDeviceSpecificResources(OCUuidUtil.uuidToString(remoteDevice.getDeviceId())));
            }

            /* check if the device is accessible via coaps get /oic/d or not
             * because no pairwised client can get STATUS_OK in secured channel(coaps)
            OcRemoteResource[] resources = remoteDevice.getResources();
            for(OcRemoteResource resource : resources) {
                if(Utils.containsList(resource.getTypes(), "oic.wk.d")){
                * //GetDoxmResponseHandler.RT_DOXM)) {
                    GetDeviceSecuredResponseHandler responseHandler = new GetDeviceSecuredResponseHandler(service, remoteDevice, resource);
                    OcUtils.doGet(resource.getUri(), Utils.getCoapsEndpoint(resource.getEndpoints()), null, responseHandler, OCQos.LOW_QOS);
                }
            }
            */
        }
    }
}
