package com.gh.gamecenter.info;

import android.app.Application;

import androidx.lifecycle.LiveData;
import androidx.annotation.NonNull;

import com.gh.common.constant.Config;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.common.baselist.ListViewModel;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.entity.ViewsEntity;
import com.gh.gamecenter.retrofit.RetrofitManager;

import java.util.List;

import io.reactivex.Observable;

/**
 * Created by khy on 19/03/18.
 */

public class InfoViewModel extends ListViewModel<NewsEntity, NewsEntity> {

    NewsViewsRepository<ViewsEntity> mNewsViewsRepository = new NewsViewsRepository<>();

    public InfoViewModel(@NonNull Application application) {
        super(application);
        LiveData<List<ViewsEntity>> listLiveData = mNewsViewsRepository.asLiveData();
        mResultLiveData.addSource(listLiveData, viewsEntities -> {
            List<NewsEntity> value = mListLiveData.getValue();
            if (value != null && viewsEntities != null)
                for (ViewsEntity viewsEntity : viewsEntities) {
                    for (NewsEntity newsEntity : value) {
                        if (viewsEntity.getId().equals(newsEntity.getId())) {
                            newsEntity.setViews(viewsEntity.getViews());
                            break;
                        }
                    }
                }
            mResultLiveData.postValue(NewsEntity.Companion.deepCopy(value));
        });
    }

    @Override
    protected void mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData, list -> {
            if (list == null) return;
            mResultLiveData.postValue(NewsEntity.Companion.deepCopy(list));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                NewsEntity newsEntity = list.get(i);
                if (newsEntity.getViews() == 0) {
                    builder.append(newsEntity.getId());
                    builder.append("-");
                }
            }
            if (builder.length() > 0) {
                builder.deleteCharAt(builder.length() - 1);
                String ids = builder.toString();
                mNewsViewsRepository.getNewsViews(RetrofitManager
                        .getInstance()
                        .getApi()
                        .getArticlesVisits(UrlFilterUtils.getFilterQuery("article_ids", ids)));
            }
        });
    }

    @Override
    public Observable<List<NewsEntity>> provideDataObservable(int offset) {
        return RetrofitManager.getInstance().getApi()
                .getArticleList(UrlFilterUtils.getFilterQuery("type_group", "资讯"), offset);
    }

    @Override
    protected List<NewsEntity> filterData(@NonNull List<NewsEntity> list) {
        return list;
    }
}
