package org.deviceconnect.android.deviceplugin.hvcc2w.profile;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import org.deviceconnect.android.deviceplugin.hvcc2w.BuildConfig;
import org.deviceconnect.android.deviceplugin.hvcc2w.manager.HVCManager;
import org.deviceconnect.android.deviceplugin.hvcc2w.manager.data.HVCCameraInfo;
import org.deviceconnect.android.profile.DConnectProfileProvider;
import org.deviceconnect.android.profile.ServiceDiscoveryProfile;
import org.deviceconnect.message.DConnectMessage;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * HVCC2W Service Discovery Profile.
 *
 * @author NTT DOCOMO, INC.
 */

public class HVCC2WServiceDiscoveryProfile extends ServiceDiscoveryProfile {

    /**
     * Constructor.
     *
     * @param provider an instance of {@link DConnectProfileProvider}
     */
    public HVCC2WServiceDiscoveryProfile(final DConnectProfileProvider provider) {
        super(provider);
    }

    @Override
    protected boolean onGetServices(final Intent request, final Intent response) {
        if (!isNetwork()) {
            return true;
        }
        HVCManager.INSTANCE.getCameraList(new HVCManager.ResponseListener() {
            @Override
            public void onReceived(String json) {

                final Map<String, HVCCameraInfo> devices = HVCManager.INSTANCE.getHVCDevices();
                final Bundle[] services = new Bundle[devices.size()];
                final int[] index = new int[1];
                index[0] = 0;
                for (String key : devices.keySet()) {
                    final HVCCameraInfo camera = devices.get(key);
                    HVCManager.INSTANCE.setCamera(camera.getID(), new HVCManager.ResponseListener() {
                        @Override
                        public void onReceived(String json) {
                            if (json == null) {
                                return;
                            }
                            try {
                                JSONObject result = new JSONObject(json);
                                if (result.getInt("result") != 1) {
                                    return;
                                }
                            } catch (JSONException e) {
                                if (BuildConfig.DEBUG) {
                                    e.printStackTrace();
                                }
                                return;
                            }

                            Bundle service = new Bundle();
                            ServiceDiscoveryProfile.setId(service, camera.getID());
                            ServiceDiscoveryProfile.setName(service, camera.getName());
                            ServiceDiscoveryProfile.setType(service, NetworkType.WIFI);
                            ServiceDiscoveryProfile.setOnline(service, true);
                            ServiceDiscoveryProfile.setScopes(service, getProfileProvider());
                            services[index[0]++] = service;
                            setServices(response, services);
                            setResult(response, DConnectMessage.RESULT_OK);
                            sendResponse(response);
                        }
                    });
                }
            }
        });
        return false;
    }

    private boolean isNetwork(){
        ConnectivityManager cm =  (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null){
            return info.isConnected();
        } else {
            return false;
        }
    }
}

@@ -702,16 +702,60 @@
 til.Map;
+%0Aimport java.util.concurrent.CountDownLatch;
 %0A%0A/**%0A *
@@ -1608,16 +1608,106 @@
 ize()%5D;%0A
+                final CountDownLatch countDownLatch = new CountDownLatch(devices.size());%0A
         
@@ -3293,32 +3293,214 @@
 ervice;%0A        
+                    countDownLatch.countDown();%0A                        %7D%0A                    %7D);%0A                %7D%0A                try %7B%0A                    countDownLatch.await();%0A
                 
@@ -3536,24 +3536,16 @@
 vices);%0A
-        
         
@@ -3624,43 +3624,87 @@
     
-            sendResponse(response);
+%7D catch (InterruptedException e) %7B%0A                    if (BuildConfig.DEBUG) %7B
 %0A   
@@ -3716,33 +3716,52 @@
                 
-%7D
+e.printStackTrace();
 %0A               
@@ -3758,34 +3758,32 @@
                %7D
-);
 %0A               
@@ -3777,32 +3777,72 @@
               %7D%0A
+                sendResponse(response);%0A
             %7D%0A  

Fix sync for service discovery response