package com.nestedworld.nestedworld.database.updater.base;

import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;

import com.nestedworld.nestedworld.database.updater.callback.OnEntityUpdated;
import com.nestedworld.nestedworld.network.http.implementation.NestedWorldHttpApi;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Response;

public abstract class EntityUpdater<T> {
    protected final static String TAG = EntityUpdater.class.getSimpleName();
    private final NestedWorldHttpApi mNestedWorldHttpApi;

    /*
    ** Constructor
     */
    protected EntityUpdater() {
        mNestedWorldHttpApi = NestedWorldHttpApi.getInstance();
    }

    /*
    ** Method every child will have to implement
     */
    @NonNull
    protected abstract Call<T> getRequest();

    protected abstract void updateEntity(@NonNull final Response<T> response);

    /*
    ** Public method
     */
    @WorkerThread
    public boolean run() {
        return makeRequest();
    }

    public void start(@NonNull final OnEntityUpdated onEntityUpdated) {
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                return makeRequest();
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (result) {
                    onEntityUpdated.onSuccess();
                } else {
                    onEntityUpdated.onError(OnEntityUpdated.KIND.SERVER);
                }
            }
        }.execute();
    }

    /*
    ** Utils for child
     */
    protected NestedWorldHttpApi getApi() {
        return mNestedWorldHttpApi;
    }

    /*
    ** Internal method
     */
    private boolean makeRequest() {
        Call<T> request = getRequest();

        try {
            Response<T> response = request.execute();
            if (response != null && response.isSuccessful()) {
                updateEntity(response);
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

@@ -121,24 +121,68 @@
 on.NonNull;%0A
+import android.support.annotation.Nullable;%0A
 import andro
@@ -1119,22 +1119,23 @@
 start(@N
-onN
 ull
+able
  final O
@@ -1426,32 +1426,83 @@
 olean result) %7B%0A
+                if (onEntityUpdated != null) %7B%0A    
                 
@@ -1527,32 +1527,36 @@
                 
+   
+ 
 onEntityUpdated.
@@ -1576,32 +1576,36 @@
                 
+    
 %7D else %7B%0A       
@@ -1589,32 +1589,36 @@
        %7D else %7B%0A
+    
                 
@@ -1675,16 +1675,38 @@
 ERVER);%0A
+                    %7D%0A
         

allow friend update without callback