package com.gh.gamecenter.qa.subject;

import android.app.Application;

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

import com.gh.gamecenter.common.baselist.ListHeadViewModel;
import com.gh.gamecenter.common.baselist.LoadType;
import com.gh.gamecenter.common.entity.CommunityEntity;
import com.gh.gamecenter.common.mvvm.Resource;
import com.gh.gamecenter.common.mvvm.Status;
import com.gh.gamecenter.feature.entity.AnswerEntity;
import com.gh.gamecenter.qa.entity.AskSubjectEntity;
import com.gh.gamecenter.retrofit.RetrofitManager;

import java.util.List;

import io.reactivex.Observable;

/**
 * Created by khy on 1/04/18.
 */

public class AskSubjectViewModel extends ListHeadViewModel<AnswerEntity, AnswerEntity, AskSubjectEntity> {

    private MutableLiveData<Resource<AskSubjectEntity>> mSubjectLiveData = new MediatorLiveData<>();
    private CommunityEntity communityData;
    private AskSubjectEntity mCacheSubjectData;
    private String columnId;

    public AskSubjectViewModel(@NonNull Application application) {
        super(application);
        mResultLiveData.addSource(mSubjectLiveData, it -> {
            if (it != null && it.status == Status.SUCCESS) {
                mCacheSubjectData = it.data;
            }
        });
    }

    @NonNull
    @Override
    protected Observable<AskSubjectEntity> provideHeadDataObservable() {
        return RetrofitManager.getInstance().getApi().getAskSubjectData(communityData.getId(), columnId);
    }

    @Override
    protected void mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData, mResultLiveData::postValue);
    }

    public AskSubjectEntity getCacheSubjectData() {
        return mCacheSubjectData;
    }

    public CommunityEntity getCommunityData() {
        return communityData;
    }

    public void initData(CommunityEntity community, String columnId) {
        this.communityData = community;
        this.columnId = columnId;
        load(LoadType.REFRESH);
    }

    @Override
    public Observable<List<AnswerEntity>> provideDataObservable(int page) {
        return RetrofitManager.getInstance().getApi()
                .getAskSubjectColumnAnswers(communityData.getId(), columnId, page, "recommend", 20);
    }
}
