package it.integry.integrywmsnative.core.REST.consumers;

import android.util.Log;

import it.integry.integrywmsnative.core.REST.model.EsitoType;
import it.integry.integrywmsnative.core.REST.model.ServiceRESTResponse;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityString;
import retrofit2.Response;

public class _BaseRESTConsumer {


    public static <T> void analyzeAnswer(Response<ServiceRESTResponse<T>> response, String logTitle, final ISimpleOperationCallback<T> callback){
        if(response.isSuccessful()) {
            if(response.body() != null) {
                if(response.body().getEsito() == EsitoType.OK) {
                    if(!UtilityString.isNullOrEmpty(response.body().getErrorMessage())){
                        callback.onFailed(new Exception(response.body().getErrorMessage()));
                    } else callback.onSuccess(response.body().getDto());
                } else {
                    Log.e(logTitle, response.body().getErrorMessage());
                    callback.onFailed(new Exception(response.body().getErrorMessage()));
                }
            } else {
                Log.e(logTitle, response.message());
                callback.onFailed(new Exception(response.message()));
            }
        } else {
            Log.e(logTitle, "Status " + response.code() + ": " + response.message());
            callback.onFailed(new Exception("Status " + response.code() + ": " + response.message()));
        }
    }

    public static <T> void analyzeAnswer(Response<ServiceRESTResponse<T>> response, String logTitle, RunnableArgs<T> onComplete, RunnableArgs<Exception> onFailed){
        analyzeAnswer(response, logTitle, new ISimpleOperationCallback<T>() {
            @Override
            public void onSuccess(T value) {
                onComplete.run(value);
            }

            @Override
            public void onFailed(Exception ex) {
                onFailed.run(ex);
            }
        });
    }

}
