package com.tjzhxx.union.public_store.rx;

import android.content.Context;

import com.tjzhxx.union.R;
import com.tjzhxx.union.dialog.SessionPromptDialog;
import com.tjzhxx.union.entity.BaseResponse;
import com.tjzhxx.union.public_store.FNNetwork;
import com.tjzhxx.union.public_store.LogUtils;
import com.tjzhxx.union.system.BaseActivity;
import com.tjzhxx.union.system.MyApplication;

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

/**
 * 描述:
 *
 * @author yanghuaxiong
 * @create 2018/6/8 下午8:16
 */
public abstract class DefaultSubscriber<T> implements Observer<T> {
    private Context mContext;

    public DefaultSubscriber(Context mContext) {
        this.mContext = mContext;
    }

    public abstract void success(T t);

    @Override
    public void onSubscribe(Disposable d) {
        if (!FNNetwork.isConnected(MyApplication.getInstance())) {
            d.dispose();
            if (mContext instanceof BaseActivity) {
                ((BaseActivity) mContext).showSnackBar(mContext.getString(R.string.global_tips_network_error));
            }
            return;
        }
    }

    @Override
    public void onComplete() {

    }

    public void onErr(T t) {
        LogUtils.e("TAG",t.toString());
    }

    @Override
    public void onNext(T t) {
        if (t != null) {
            if (t instanceof BaseResponse) {

                if (((BaseResponse) t).getCode() == -1) {
                    SessionPromptDialog sessionPromptDialog = new SessionPromptDialog(mContext);
                    sessionPromptDialog.setCancelAble(false);
                    sessionPromptDialog.show();
                } else if (((BaseResponse) t).getCode() == 200 ||((BaseResponse) t).getStatus() == 1 ) {
                    success(t);
                } else {
                    onErr(t);
                    ((BaseActivity) mContext).showSnackBar(((BaseResponse) t).getMsg());
                }
            }else {
                success(t);
            }
        } else {
            onErr(t);
            if (mContext instanceof BaseActivity) {
                ((BaseActivity) mContext).showSnackBar(mContext.getString(R.string.loading_error));
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (mContext instanceof BaseActivity) {
            ((BaseActivity) mContext).showSnackBar(mContext.getString(R.string.loading_error));
        }
    }

}
