package com.gh.gamecenter.common.baselist;

import android.app.Application;

import androidx.lifecycle.MutableLiveData;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gh.gamecenter.common.mvvm.Resource;
import com.gh.gamecenter.common.retrofit.Response;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

public abstract class ListHeadViewModel<LD, ID, HD> extends ListViewModel<LD, ID> {

    protected final MutableLiveData<Resource<HD>> mHeadLiveData = new MutableLiveData<>();

    public ListHeadViewModel(@NonNull Application application) {
        super(application);
    }

    @NonNull
    protected abstract Observable<HD> provideHeadDataObservable();

    private void loadHeadData() {
        provideHeadDataObservable().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<HD>() {
                    @Override
                    public void onResponse(@Nullable HD response) {
                        mHeadLiveData.postValue(Resource.success(response));
                        mLoadStatusLiveData.setValue(LoadStatus.INIT_LOADED);
                        loadData();
                    }

                    @Override
                    public void onFailure(@Nullable HttpException e) {
                        if (e != null && e.code() == 404) {
                            mLoadStatusLiveData.setValue(LoadStatus.INIT_EXCEPTION);
                        } else {
                            mLoadStatusLiveData.setValue(LoadStatus.INIT_FAILED);
                        }
                        mHeadLiveData.postValue(Resource.error(e));
                    }
                });
    }

    protected void loadStatusControl(int size) {
        if (size == REQUEST_FAILURE_SIZE) {
            mLoadStatusLiveData.setValue(LoadStatus.LIST_FAILED);
        } else if (size == 0 || size < mOverLimitSize) {
            mLoadStatusLiveData.setValue(LoadStatus.LIST_OVER);
        } else {
            mLoadStatusLiveData.setValue(LoadStatus.LIST_LOADED);
        }

        if (size == REQUEST_FAILURE_SIZE) {
            mRetryParams = mCurLoadParams;
        } else {
            mRetryParams = null;
            mCurLoadParams.setLoadOffset(mCurLoadParams.getLoadOffset() + 1); // 页数 + 1
        }
    }

    public MutableLiveData<Resource<HD>> getHeadLiveData() {
        return mHeadLiveData;
    }

    @Override
    public void load(LoadType loadType) {
        if (loadType == LoadType.REFRESH || mHeadLiveData.getValue() == null) {
            initLoadParams();
            loadHeadData();
        } else if (loadType == LoadType.RETRY) {
            mLoadStatusLiveData.setValue(LoadStatus.LIST_LOADED);
            loadData();
        } else {
            loadData();
        }
    }
}
