package com.gh.gamecenter.forum.home

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.feature.entity.TimeEntity
import com.gh.gamecenter.feature.entity.UserEntity
import com.gh.gamecenter.livedata.Event
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
import com.gh.gamecenter.retrofit.RetrofitManager

class CommunityHomeViewModel(application: Application) : AndroidViewModel(application) {

    private val mApi = RetrofitManager.getInstance().api
    val articleLiveData = MediatorLiveData<ArticleEntity>()

    fun getArticleData(articleId: String) {
        mApi.getCommunityArticleDetail(articleId)
            .compose(observableToMain())
            .subscribe(object : Response<ArticleDetailEntity>() {
                override fun onResponse(response: ArticleDetailEntity?) {
                    response?.run {
                        articleLiveData.postValue(convertArticleDetailToArticle(response))
                    }

                }
            })
    }

    fun getQuestionDetail(questionId: String) {
        mApi.getQuestionsById(questionId)
            .compose(observableToMain())
            .subscribe(object : Response<QuestionsDetailEntity>() {
                override fun onResponse(response: QuestionsDetailEntity?) {
                    response?.run {
                        articleLiveData.postValue(convertQuestionDetailToArticle(response))
                    }
                }
            })
    }

    fun getVideoDetail(videoId: String) {
        mApi.getBbsVideoDetail(videoId)
            .compose(observableToMain())
            .subscribe(object : Response<ForumVideoEntity>() {
                override fun onResponse(response: ForumVideoEntity?) {
                    response?.run {
                        articleLiveData.postValue(convertVideoDetailToArticle(response))
                    }
                }
            })
    }

    fun convertArticleDetailToArticle(articleDetailEntity: ArticleDetailEntity): ArticleEntity {
        val articleEntity = ArticleEntity()

        articleEntity.id = articleDetailEntity.id
        articleEntity.brief =
            articleDetailEntity.content.removeVideoContent().removeInsertedContent().clearHtmlFormatCompletely()
        articleEntity.count = articleDetailEntity.count
        articleDetailEntity.community.id = articleDetailEntity.communityId
        articleEntity.community = articleDetailEntity.community
        articleEntity.community = articleDetailEntity.community
        articleEntity.time = articleDetailEntity.time
        articleEntity.title = articleDetailEntity.title
        articleEntity.user = articleDetailEntity.user
        articleEntity.images = articleDetailEntity.images
        articleEntity.imagesInfo = articleDetailEntity.imagesInfo
        articleEntity.videos = articleDetailEntity.videos
        articleEntity.status = articleDetailEntity.status ?: ""
        articleEntity.type = "community_article"

        return articleEntity
    }

    fun convertQuestionDetailToArticle(questionDetailEntity: QuestionsDetailEntity): ArticleEntity {
        val articleEntity = ArticleEntity()

        articleEntity.id = questionDetailEntity.id ?: ""
        articleEntity.brief =
            questionDetailEntity.description?.removeVideoContent()?.removeInsertedContent()?.clearHtmlFormatCompletely()
                ?: ""
        articleEntity.count = questionDetailEntity.count
        articleEntity.community = questionDetailEntity.community
        articleEntity.community = questionDetailEntity.community
        articleEntity.time = questionDetailEntity.time
        articleEntity.title = questionDetailEntity.title ?: ""
        articleEntity.user = questionDetailEntity.user
        articleEntity.images = questionDetailEntity.images
        articleEntity.imagesInfo = questionDetailEntity.imagesInfo
        articleEntity.videos = questionDetailEntity.videos
        articleEntity.status = questionDetailEntity.status
        articleEntity.type = "question"

        return articleEntity
    }

    fun convertVideoDetailToArticle(forumVideoEntity: ForumVideoEntity): ArticleEntity {
        val articleEntity = ArticleEntity()

        articleEntity.id = forumVideoEntity.id
        articleEntity.title = forumVideoEntity.title
        articleEntity.des = forumVideoEntity.des
        articleEntity.url = forumVideoEntity.url
        articleEntity.status = forumVideoEntity.status
        articleEntity.poster = forumVideoEntity.poster
        articleEntity.length = forumVideoEntity.length
        articleEntity.videoInfo = forumVideoEntity.videoInfo
        articleEntity.count = forumVideoEntity.count
        articleEntity.community = forumVideoEntity.bbs ?: CommunityEntity()
        articleEntity.time = TimeEntity(upload = forumVideoEntity.time.upload)
        articleEntity.title = forumVideoEntity.title
        forumVideoEntity.user.run {
            articleEntity.user = UserEntity(
                id = id,
                name = name,
                icon = icon,
                auth = auth,
                badge = badge,
                border = border
            )
        }
        articleEntity.type = "video"

        return articleEntity
    }

    private val _hasFollowedUsers = MutableLiveData<Boolean>()
    val hasFollowedUser: LiveData<Boolean> = _hasFollowedUsers
    fun updateHasFollowUser(show: Boolean) {
        _hasFollowedUsers.value = show
    }

    private val filterDrawableResId = MutableLiveData<Int?>()
    fun updateFilterResId(resId: Int?) {
        filterDrawableResId.value = resId
    }

    val followFilterStatus = MediatorLiveData<Int?>().apply {
        addSource(hasFollowedUser) {
            if (it) {
                value = filterDrawableResId.value
            } else {
                value = null
            }
        }

        addSource(filterDrawableResId) { resId ->
            // 当 hasFollowedUser.value == null 时，不需要调用setValue
            if (hasFollowedUser.value == true) {
                value = resId
            } else if (hasFollowedUser.value == false) {
                value = null
            }
            when {
                resId == null ||
                        hasFollowedUser.value == false -> {
                    // 当resId == null 时，表示已切换到别的tab 直接setValue
                    // 当 resId != null && hasFollowedUser,value 为false时，说明关注页数据已加载完毕，并且没有关注任何用户，直接setValue
                    value = null
                }

                hasFollowedUser.value == true -> {
                    // 当 resId ！= null 且 有关注用户，显示当前 resId
                    value = resId
                }

                else -> {
                    // do Nothing 当resId != null ，但是hasFollowedUser.value == null,说明关注页数据正在loading，等待，无需setValue
                }

            }
        }
    }

    private val _filterFollowedAction = MutableLiveData<Event<Int>>()
    val filterFollowedAction: LiveData<Event<Int>> = _filterFollowedAction
    fun filterFollowed(position: Int) {
        val filterName = when (position) {
            0 -> "全部"
            1 -> "关注的人"
            else -> "关注的游戏"
        }
        SensorsBridge.trackFollowTabFilterOptionClick(filterName)
        _filterFollowedAction.value = Event(position)
    }
}