package com.ccwangluo.accelerator.ui.news

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccwangluo.accelerator.model.NewsModel
import com.ccwangluo.accelerator.utils.http.HttpGo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class NewsObjectModel : ViewModel() {
    val newsModel = MutableLiveData<NewsModel>()


    fun freshData(position: String, gameId: Int, page: Int) {
        val type = when (position) {
            "1" -> 1
            "2" -> 2
            "3" -> 5
            "4" -> 4
            else -> ""
        }
        viewModelScope.launch(Dispatchers.IO) {
            val res =
                HttpGo.getSync<NewsModel>("/api/new/all/list?gameId=$gameId&page=$page&size=10&type=$type")
            res?.let {
                if (it.code == 200) {
                    it.data?.let {
                        newsModel.postValue(it)
                    }
                }
            }
        }
    }

    /**
     * 点赞
     */
    fun greate(type: Int?,parentId : Int, gameId: Int, callback: () -> Unit) {
        val map = mutableMapOf<String, String>()
        map.put("gameId", gameId.toString())
        map.put("parentId",parentId.toString())
        type?.let {
            map.put("type", it.toString())
        }
        viewModelScope.launch(Dispatchers.IO) {
            val res =
                HttpGo.postSync<String>("/api/new/great", map)
            res?.let {
                if (it.code == 200) {
                    withContext(Dispatchers.Main) {
                        callback()
                    }
                }
            }
        }
    }
}