package com.gh.gamecenter.collection;

import android.app.Application;

import com.gh.gamecenter.core.AppExecutor;
import com.gh.common.history.HistoryDatabase;
import com.gh.common.history.HistoryHelper;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.common.baselist.ListViewModel;
import com.gh.gamecenter.common.baselist.LoadType;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.entity.ViewsEntity;
import com.gh.gamecenter.info.NewsViewsRepository;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.retrofit.RetrofitManager;

import java.util.ArrayList;
import java.util.List;

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

import io.reactivex.Observable;
import io.reactivex.Single;

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

public class ArticleViewModel extends ListViewModel<NewsEntity, NewsEntity> {

    public String type;

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

    public ArticleViewModel(@NonNull Application application) {
        super(application);
        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)));
            }
        });

        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() {

    }

    @Override
    public Single<List<NewsEntity>> provideDataSingle(int page) {
        if (ArticleFragment.COLLECTION.equals(type)) {
            return Single.fromObservable(RetrofitManager.getInstance().getApi().getCollectionArticle(UserManager.getInstance().getUserId(), page));
        } else {
            if (page > 5) {
                return Single.create(emitter -> emitter.onSuccess(new ArrayList<>()));
            }
            return HistoryDatabase.Companion.getInstance().newsDao().getNewsWithOffset(20, (page - 1) * 20);
        }
    }

    @Override
    public Observable<List<NewsEntity>> provideDataObservable(int page) {
        return null;
    }

    public void removeHistory(NewsEntity newsEntity) {
        List<NewsEntity> originList = mResultLiveData.getValue();
        if (originList != null) {
            HistoryHelper.deleteNewsEntity(newsEntity.getId());
            originList.remove(newsEntity);
            if (originList.size() == 0) {
                AppExecutor.getUiExecutor().executeWithDelay(() -> {
                    load(LoadType.REFRESH);
                }, 100);
            } else {
                mResultLiveData.postValue(originList);
            }
        }
    }

    public void removeHistories(List<String> ids) {
        List<NewsEntity> originList = mResultLiveData.getValue();
        if (originList != null) {
            for (String id : ids) {
                HistoryHelper.deleteNewsEntity(id);
                for (int i = 0; i < originList.size(); i++) {
                    if (originList.get(i).getId().equals(id)) {
                        originList.remove(originList.get(i));
                        i--;
                    }
                }
            }

            if (originList.size() == 0) {
                AppExecutor.getUiExecutor().executeWithDelay(() -> load(LoadType.REFRESH), 100);
            } else {
                mResultLiveData.postValue(originList);
            }
        }
    }
}
