package com.tofly.latte_core.net.observer;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import com.tofly.latte_core.utils.LoaderUtils;

import io.reactivex.disposables.Disposable;

/**
 * 加载进度条
 */
public abstract class MyObserver<T> extends BaseObserver<T> {

    private boolean mShowDialog;
    private Context mContext;

    public MyObserver(Context context, Boolean showDialog) {
        mContext = context;
        mShowDialog = showDialog;
    }

    public MyObserver(Context context) {
        this(context, true);
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (!isConnected(mContext)) {
            Toast.makeText(mContext, "未连接网络", Toast.LENGTH_SHORT).show();
            cancleRequest();
        } else {
            if (mShowDialog) {
                LoaderUtils.getInstance().showDialog(mContext);
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (!isConnected(mContext))
            cancleRequest();
        super.onError(e);
        hidDialog();
    }

    @Override
    public void onComplete() {
        if (!isConnected(mContext))
            cancleRequest();
        super.onComplete();
        hidDialog();
    }

    public void hidDialog() {
        if (mShowDialog) {
            LoaderUtils.getInstance().stopDialog();
        }
    }

    /**
     * 是否有网络连接，不管是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() {
        hidDialog();
    }

}
