package com.offline.music.playermp3.network;

import com.offline.music.playermp3.api.RequestListener;
import com.offline.music.playermp3.helper.CommonUtils;

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

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public class ObserverWrapper<T> implements Observer<T> {
    private RequestListener<T> requestListener;

    public ObserverWrapper(RequestListener<T> requestListener) {
        this.requestListener = requestListener;
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T t) {
        ResponseBody responseBody = (ResponseBody) t;
        JSONObject jsonObject = CommonUtils.toJsonObject(responseBody);
        try {
            if (jsonObject != null) {
                if (jsonObject.has("playabilityStatus")) {
                    String status = jsonObject.getJSONObject("playabilityStatus").getString("status");
                    if (!status.equals("OK")) {
                        requestListener.onFail("");
                        return;
                    }

                }
                requestListener.onSuccess(jsonObject);
            }

        } catch (JSONException e) {
            requestListener.onFail(e.getMessage());
        }


    }

    @Override
    public void onError(Throwable e) {
        CommonUtils.LogMsg("----------onError---" + e.getMessage());
        requestListener.onFail(e.getMessage());
    }

    @Override
    public void onComplete() {

    }
}

