package it.near.sdk.operation;

import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.auth.AuthenticationException;
import it.near.sdk.GlobalConfig;
import it.near.sdk.communication.Constants;
import it.near.sdk.communication.NearAsyncHttpClient;
import it.near.sdk.communication.NearJsonHttpResponseHandler;
import it.near.sdk.logging.NearLog;
import it.near.sdk.utils.NearJsonAPIUtils;

public class NearItUserDataAPI {

    private static final String TAG = "NearItUserDataAPI";
    private static final String PLUGIN_NAME = "congrego";
    private static final String PROFILE_RES_TYPE = "profiles";
    private static final String DATA_POINTS_RES_TYPE = "data_points";

    private final GlobalConfig globalConfig;
    private final NearAsyncHttpClient httpClient;

    public NearItUserDataAPI(GlobalConfig globalConfig, NearAsyncHttpClient httpClient) {
        this.globalConfig = globalConfig;
        this.httpClient = httpClient;
    }

    public void sendDataPoints(@NonNull final HashMap<String, String> userData, final UserDataSendListener listener) {
        String profileId = globalConfig.getProfileId();
        HashMap<String, Object> userDataConv = new HashMap<>();
        userDataConv.putAll(userData);
        if (!userDataConv.isEmpty()) {
            if (profileId != null) {
                String reqBody;
                try {
                    reqBody = NearJsonAPIUtils.toJsonAPI("data_points", userDataConv);
                } catch (JSONException e) {
                    NearLog.d(TAG, "Error creating userdata request");
                    listener.onSendingFailure();
                    return;
                }

                Uri url = Uri.parse(Constants.API.PLUGINS_ROOT).buildUpon()
                        .appendPath(PLUGIN_NAME)
                        .appendPath(PROFILE_RES_TYPE)
                        .appendPath(profileId)
                        .appendPath(DATA_POINTS_RES_TYPE).build();

                try {
                    httpClient.nearPost(url.toString(), reqBody, new NearJsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            NearLog.d(TAG, "datapoint created: " + response.toString());
                            listener.onSendingSuccess(userData);
                        }

                        @Override
                        public void onFailureUnique(int statusCode, Header[] headers, Throwable throwable, String responseString) {
                            NearLog.d(TAG, "datapoint not created, network error: " + statusCode);
                            listener.onSendingFailure();
                        }
                    });
                } catch (AuthenticationException | UnsupportedEncodingException e) {
                    NearLog.d(TAG, "error: impossible to send requests");
                }
            }
        }
    }

    public static NearItUserDataAPI obtain(GlobalConfig globalConfig, Context context) {
        return new NearItUserDataAPI(globalConfig, new NearAsyncHttpClient(context));
    }

    interface UserDataSendListener {
        void onSendingSuccess(HashMap<String, String> sentData);

        void onSendingFailure();
    }
}

@@ -247,20 +247,70 @@
 va.util.
-Hash
+ArrayList;%0Aimport java.util.HashMap;%0Aimport java.util.
 Map;%0A%0Aim
@@ -1433,16 +1433,106 @@
         
+if (!userData.isEmpty()) %7B%0A            if (profileId != null) %7B%0A                ArrayList%3C
 HashMap%3C
@@ -1550,155 +1550,341 @@
 ect%3E
- userDataConv = new HashMap%3C%3E();%0A        userDataConv.putAll(userData);%0A        if (!userDataConv.isEmpty()) %7B%0A            if (profileId != null) %7B
+%3E maps = new ArrayList%3C%3E();%0A                for (Map.Entry%3CString, String%3E entry : userData.entrySet()) %7B%0A                    HashMap%3CString, Object%3E map = new HashMap%3C%3E();%0A                    map.put(%22key%22, entry.getKey());%0A                    map.put(%22value%22, entry.getValue());%0A                    maps.add(map);%0A                %7D
 %0A   
@@ -2010,20 +2010,12 @@
 s%22, 
-userDataConv
+maps
 );%0A 

fix wrong request body