package co.pixelbeard.theanfieldwrap.networking;

import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;

import co.pixelbeard.theanfieldwrap.utils.BaseView;
import io.reactivex.observers.DisposableObserver;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

public abstract class CallbackWrapper<T extends BaseResponse> extends DisposableObserver<T> {

    private BaseView view;

    public CallbackWrapper(BaseView view) {
        this.view = view;
    }

    @Override
    public void onNext(T t) {

        if (t != null && view != null) {
            if (t.isSuccess()) {
                onSuccess(t);
            } else if (t.getMessage().equals("Invalid Token")) {
                view.logoutUser();
            } else {
                onSuccessFalse(t);
            }
        } else onError(new Exception("Null Response from server"));
    }

    @Override
    public void onError(Throwable t) {
        if (view != null) {
            view.hideLoader();
            t.printStackTrace();
            if (t instanceof HttpException) {
                ResponseBody responseBody = ((HttpException) t).response().errorBody();
                view.onUnknownError(getErrorMessage(responseBody));
            } else if (t instanceof SocketTimeoutException) {
                view.onTimeout();
            } else if (t instanceof IOException) {
                view.onNetworkError();
            } else {
                view.onUnknownError(t.getMessage());
            }
        }
    }

    @Override
    public void onComplete() {
        if (view != null) {
            view.hideLoader();
        }
    }

    protected abstract void onSuccess(T t);

    protected abstract void onSuccessFalse(T t);

    private String getErrorMessage(ResponseBody responseBody) {
        try {
            JSONObject jsonObject = new JSONObject(responseBody.string());
            return jsonObject.getString("message");
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}