package com.tofly.latte_core.net.observer;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.tofly.latte_core.config.Latte;
import com.tofly.latte_core.net.exception.ExceptionHandle;

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

/**
 * rxJava观察者封装
 */
public abstract class BaseObserver<T> implements Observer<T> {

    private static final String TAG = "BaseObserver";

    private Disposable disposable;

    @Override
    public void onSubscribe(Disposable d) {
        Log.e(TAG, "onSubscribe: ");
        disposable = d;
        if (!isConnected(Latte.getApplicationContext()))
            cancleRequest();
    }

    @Override
    public void onNext(T response) {
        if (!isConnected(Latte.getApplicationContext())) {
            cancleRequest();
        } else {
            onSuccess(response);
        }
    }

    @Override
    public void onError(Throwable e) {
        if (!isConnected(Latte.getApplicationContext())) {
            cancleRequest();
        } else {
            if (e != null)
                onFailure(e, ExceptionHandle.handleException(e).getMessage());
        }

    }

    @Override
    public void onComplete() {
        if (!isConnected(Latte.getApplicationContext()))
            cancleRequest();
    }

    public abstract void onSuccess(T demo);

    public abstract void onFailure(Throwable e, String errorMsg);

    /**
     * 是否有网络连接，不管是wifi还是数据流量
     *
     * @param context
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }
        return info.isAvailable();
    }

    /**
     * 取消订阅
     */
    public void cancleRequest() {
        if (disposable != null && disposable.isDisposed())
            disposable.dispose();
    }

}
