package com.gh.gamecenter.mygame

import android.app.Application
import com.gh.common.filter.RegionSettingHelper
import com.gh.common.util.ApkActiveUtils
import com.gh.common.util.ConcernUtils
import com.gh.common.util.DataCollectionUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.Observable

class MyFollowedGameViewModel(application: Application) : ListViewModel<GameEntity, GameEntity>(application) {

    override fun provideDataObservable(page: Int): Observable<MutableList<GameEntity>>? {
        return RetrofitManager.getInstance().api
            .getConcern(UserManager.getInstance().userId)
            .map(RegionSettingHelper.filterGame)
            .map(ApkActiveUtils.filterMapperList)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            it.forEach { game -> game.hideSizeInsideDes = true }
            mResultLiveData.postValue(it)
        }
    }

    fun getListData(): List<GameEntity> {
        return mListLiveData.value ?: listOf()
    }

    fun unfollowGame(gameEntity: GameEntity) {
        ConcernUtils.deleteConcernData(getApplication(),
            gameEntity.id,
            object : ConcernUtils.onConcernListener {
                override fun onSuccess() {
                    DataCollectionUtils.uploadConcern(
                        getApplication(),
                        gameEntity.name,
                        gameEntity.id,
                        HaloApp.getInstance().application.getString(R.string.cancel_concern)
                    )

                    removeFollowLocally(gameEntity.id)
                }

                override fun onError() {
                    Utils.toast(getApplication(), R.string.concern_cancel_failure)
                }
            })
    }

    fun removeFollowLocally(gameId: String) {
        mListLiveData.value?.let {
            val iterator = it.iterator()
            var deleteModeOn = false

            while (iterator.hasNext()) {
                val game = iterator.next()
                if (game.id == gameId) {
                    deleteModeOn = true
                    iterator.remove()
                    continue
                }
                if (deleteModeOn && game.isRelated) {
                    if (game.isRelated) {
                        iterator.remove()
                        continue
                    } else {
                        break
                    }
                }
            }

            if (it.size == 0) {
                load(LoadType.REFRESH)
            } else {
                mListLiveData.postValue(it)
            }
        }
    }
}