package it.near.sdk.operation;

import java.util.HashMap;

public class NearItUserProfiler implements NearItUserDataAPI.UserDataSendListener {

    private static final String TAG = "NearItUserProfiler";

    private final UserDataCacheManager userDataCacheManager;
    private final NearItUserDataAPI userDataAPI;
    private final UserDataTimer timer;

    private HashMap<String, String> userData;
    private boolean hasTimer = false;
    private boolean isBusy = false;

    NearItUserProfiler(UserDataCacheManager userDataCacheManager, NearItUserDataAPI userDataAPI, UserDataTimer timer) {
        this.userDataCacheManager = userDataCacheManager;
        this.userDataAPI = userDataAPI;
        this.timer = timer;
    }

    public void setUserData(String key, String value) {
        if (!hasTimer) {
            hasTimer = true;
            timer.start(new UserDataTimer.TimerListener() {
                @Override
                public void sendNow() {
                    startSend();
                }
            });
        }
        userDataCacheManager.setUserData(key, value);
    }

    public void sendDataPoints() {
        userData = userDataCacheManager.getUserData();
        isBusy = true;
        userDataAPI.sendDataPoints(userData, this);
    }

    public void clearUserData() {
        userDataCacheManager.removeAllData();
    }

    private void startSend() {
        shouldSendDataPoints();
        hasTimer = false;
    }

    private void shouldSendDataPoints() {
        if (userDataCacheManager.hasData()) {
            userData = userDataCacheManager.getUserData();
            isBusy = true;
            userDataAPI.sendDataPoints(userData, this);
        }
    }

    @Override
    public void onSendingSuccess(HashMap<String, String> sentData) {
        isBusy = false;
        userDataCacheManager.removeSentData(sentData);
    }

    @Override
    public void onSendingFailure() {
        isBusy = false;
    }
}

@@ -133,19 +133,48 @@
 Listener
+, UserDataTimer.TimerListener
  %7B%0A
-
 %0A    pri
@@ -427,46 +427,8 @@
 ta;%0A
-    private boolean hasTimer = false;%0A
     
@@ -781,256 +781,26 @@
     
-if (!hasTimer) %7B%0A            hasTimer = true;%0A            timer.start(new UserDataTimer.TimerListener() %7B%0A                @Override%0A                public void sendNow() %7B%0A                    startSend();%0A                %7D%0A            %7D);%0A        %7D
+timer.start(this);
 %0A   
@@ -1183,34 +1183,8 @@
 ();%0A
-        hasTimer = false;%0A
     
@@ -1649,24 +1649,24 @@
 Failure() %7B%0A
-
         isBu
@@ -1682,11 +1682,81 @@
 e;%0A    %7D
+%0A%0A    @Override%0A    public void sendNow() %7B%0A        startSend();%0A    %7D
 %0A%7D%0A

implement timer listener + remove hasTimer