package com.sybotan.android.demo.viewmodel;

import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.text.TextUtils;


import com.google.gson.Gson;
import com.sybotan.android.demo.activities.BaseActivity;
import com.sybotan.android.demo.bean.BaseModel;
import com.sybotan.android.demo.bean.UniversalCellClass;
import com.sybotan.android.demo.retrofit.BaseActionEvent;
import com.sybotan.android.demo.retrofit.BaseViewModelInterface;
import com.sybotan.android.demo.retrofit.IViewModelAction;
import com.trello.rxlifecycle2.LifecycleTransformer;

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

import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by lihao on 2020/7/9.
 */
public class BaseViewModel extends ViewModel implements IViewModelAction {
    public BaseActivity mActivity;
    private MutableLiveData<BaseActionEvent> baseActionEventLiveData;
    protected LifecycleOwner lifecycleOwner;
    public Gson mGSon;
    public BaseViewModelInterface mEmitter;
    private BaseViewModel baseViewModel;
    public ArrayList<UniversalCellClass> data_Array = new ArrayList<>();

    public BaseViewModel() {
        baseActionEventLiveData = new MutableLiveData<>();
    }


    public BaseViewModel(BaseViewModelInterface object, BaseActivity activity) {
        this.mEmitter = object;
        this.mGSon = new Gson();
        baseActionEventLiveData = new MutableLiveData<>();
        mActivity = activity;
    }

    //====================================公共部分 end============================================
    protected <S> void sendRequest(Observable<BaseModel<S>> observable,
                                   Observer<? super BaseModel<S>> observer, boolean isNeedProgress) {////绑定生命周期，防止内存泄露
        if (isNeedProgress) {
            showLoading("");
        }
        observable.compose(compose(mActivity.<BaseModel<S>>bindToLifecycle())).subscribe(observer);
    }

    //====================================待办部分 end============================================
    protected <S> void sendRequest(Observable<BaseModel<S>> observable,
                                   Observer<? super BaseModel<S>> observer, boolean isNeedProgress, boolean bo) {////绑定生命周期，防止内存泄露
        if (isNeedProgress) {
            showLoading("");
        }
        observable.compose(compose(mActivity.<BaseModel<S>>bindToLifecycle(),bo)).subscribe(observer);
    }

    private <T> ObservableTransformer<T, T> compose(final LifecycleTransformer<T> lifecycle) {
        return observable
                -> observable
                .subscribeOn(Schedulers.io())//改变调用它之前代码的线程,指定的就是发射事件的线程，通常用于网络,读写文件等io密集型的操作；
                .doOnSubscribe(disposable -> {
                    // 可添加网络连接判断等
////                    if (!isHaveInternet()) {
////                        mActivity.showErrorWithStatus("请检查网络设置");
////                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//改变调用它之后代码的线程  指定的就是订阅者接收事件的线程
                .compose(lifecycle);
    }
    private <T> ObservableTransformer<T, T> compose(final LifecycleTransformer<T> lifecycle ,boolean type) {
        return observable -> observable
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .observeOn(AndroidSchedulers.mainThread())//改变调用它之后代码的线程  指定的就是订阅者接收事件的线程
                .compose(lifecycle);
    }

    @Override
    public void showLoading(String message) {
        BaseActionEvent baseActionEvent = new BaseActionEvent(BaseActionEvent.SHOW_LOADING_DIALOG);
        baseActionEvent.setMessage(message);
        baseActionEventLiveData.setValue(baseActionEvent);
    }

    @Override
    public void showErrorLoading(String message) {
        BaseActionEvent baseActionEvent = new BaseActionEvent(BaseActionEvent.SHOW_ERROR_LOAD_DIALOG);
        baseActionEvent.setMessage(message);
        baseActionEventLiveData.setValue(baseActionEvent);
    }

    @Override
    public void dismissLoading() {
        baseActionEventLiveData.setValue(new BaseActionEvent(BaseActionEvent.DISMISS_LOADING_DIALOG));
    }

    @Override
    public void showToast(String message) {
        BaseActionEvent baseActionEvent = new BaseActionEvent(BaseActionEvent.SHOW_TOAST);
        baseActionEvent.setMessage(message);
        baseActionEventLiveData.setValue(baseActionEvent);
    }

    @Override
    public MutableLiveData<BaseActionEvent> getActionLiveData() {
        return baseActionEventLiveData;
    }

    public void setLifecycleOwner(LifecycleOwner lifecycleOwner) {
        this.lifecycleOwner = lifecycleOwner;
    }

    /**
     * @param requestBean
     * @param <T>
     * @return
     */
    protected <T> RequestBody getRequestBody(T requestBean) {
        String params, contentType = "";
        if (requestBean instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) requestBean;
            params = jsonObject.toString();
        } else if (requestBean instanceof HashMap) {
            HashMap<Object, Object> hashMap = (HashMap<Object, Object>) requestBean;
            params = mGSon.toJson(hashMap);
        } else {
            params = mGSon.toJson(requestBean);
        }

        contentType = "application/json";

        RequestBody body = RequestBody.create(MediaType.parse(contentType), params);
        return body;
    }

}
