package com.gh.gamecenter.forum.home

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.*
import com.gh.common.util.CheckLoginUtils
import com.gh.gamecenter.common.utils.createRequestBodyAny
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.entity.ForumBannerEntity
import com.gh.gamecenter.entity.ForumEntity
import com.gh.gamecenter.entity.ForumUnreadEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.HttpException

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

    private val api = RetrofitManager.getInstance().api
    val banners = MediatorLiveData<List<ForumBannerEntity>>()
    val followForumsLiveData = MediatorLiveData<List<ForumEntity>?>()
    val hotForums = MediatorLiveData<List<ForumEntity>?>()
    val officialForums = MediatorLiveData<List<ForumEntity>?>()
    var followForums = arrayListOf<ForumEntity>()
    var followStatusForums = arrayListOf<ForumUnreadEntity>()

    init {
        getData()
    }

    fun getData() {
        getBanners()
        if (CheckLoginUtils.isLogin()) {
            getFollowForum()
        } else {
            getHotForum()
        }
        getOfficialForum()
    }

    @SuppressLint("CheckResult")
    fun getBanners() {
        api.forumBanners
            .compose(singleToMain())
            .subscribe(object : BiResponse<List<ForumBannerEntity>>() {
                override fun onSuccess(data: List<ForumBannerEntity>) {
                    banners.postValue(data)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getFollowForum() {
        if (followForums.isEmpty()) {
            api.getFollowsForum(UserManager.getInstance().userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Response<List<ForumEntity>>() {
                    override fun onResponse(response: List<ForumEntity>?) {
                        super.onResponse(response)
                        if (response?.isNotEmpty() == true) {
                            followForums = ArrayList(response.reversed())
                            getForumUnreadStatus()
                        } else {
                            followForumsLiveData.postValue(response)
                        }
                    }

                    override fun onFailure(e: HttpException?) {
                        super.onFailure(e)
                        followForumsLiveData.postValue(null)
                    }
                })
        } else {
            getForumUnreadStatus()
        }
    }

    @SuppressLint("CheckResult")
    fun getForumUnreadStatus() {
        if (followForums.isEmpty() || !UserManager.getInstance().isLoggedIn) return

        val requestMap = hashMapOf<String, Any>()
        followStatusForums.clear()
        followForums.forEach {
            followStatusForums.add(it.transformUnreadEntity())
        }
        requestMap["bbs"] = followStatusForums
        val body = requestMap.createRequestBodyAny()
        RetrofitManager.getInstance()
            .api
            .getForumUnreadStatus(body)
            .compose(singleToMain())
            .subscribe(object : BiResponse<List<ForumUnreadEntity>>() {

                override fun onSuccess(data: List<ForumUnreadEntity>) {
                    if (data.isNotEmpty() && data.size == followForums.size) {
                        data.forEachIndexed { index, unreadEntity ->
                            followForums[index].unread = unreadEntity.unread
                        }
                    }
                    followForumsLiveData.postValue(followForums)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    followForumsLiveData.postValue(followForums)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getHotForum() {
        api.getHotForum(1)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<ForumEntity>>() {
                override fun onResponse(response: List<ForumEntity>?) {
                    super.onResponse(response)
                    hotForums.postValue(response)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    hotForums.postValue(null)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getOfficialForum() {
        api.getOfficialForum(1)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<ForumEntity>>() {
                override fun onResponse(response: List<ForumEntity>?) {
                    super.onResponse(response)
                    officialForums.postValue(response)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    officialForums.postValue(null)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun followForum(bbsId: String, onSuccess: () -> Unit) {
        RetrofitManager.getInstance().api
            .followForum(bbsId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    onSuccess.invoke()
                }
            })
    }

    @SuppressLint("CheckResult")
    fun unFollowForum(bbsId: String, onSuccess: () -> Unit) {
        RetrofitManager.getInstance().api
            .unFollowForum(bbsId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    onSuccess.invoke()
                }
            })
    }
}