package com.rumikuru.skdumobile.components.template.viewModels

import android.content.ContentValues
import android.content.ContentValues.TAG
import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rumikuru.skdumobile.logic.local_dao.AppDatabase
import com.rumikuru.skdumobile.logic.local_dao.DatabaseProvider
import com.rumikuru.skdumobile.models.ListMessage
import com.rumikuru.skdumobile.models.Message
import com.rumikuru.skdumobile.models.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jgroups.JChannel
import org.jgroups.Receiver
import org.jgroups.View

data class MessageViewModel(
    val context: Context? = null,
) : ViewModel(), Receiver {
    private val _uiState = MutableStateFlow(ListMessage())
    val uiState: StateFlow<ListMessage> = _uiState.asStateFlow()


    private var channel: JChannel? = null
    private var messageRecive: MutableLiveData<MutableList<Message>> = MutableLiveData()
    private var db: AppDatabase? = context?.let { DatabaseProvider.getInstance(it) }
    private var user: User? = null


    init {
        user = DatabaseProvider.getInstance(context!!).userDao().getUser()
        viewModelScope.launch(Dispatchers.IO) {
            start()
            getData()
        }

    }

    @Throws(Exception::class)
    private suspend fun start() {
        channel = JChannel()
        channel!!.receiver = this
        channel!!.connect("ChatCluster")
    }

    private suspend fun getData() {
        val messageDao = db?.messageDao()
        val messages = messageDao?.getMessages()
        //messageRecive.value = messages
        _uiState.update { currentState -> currentState.copy(messages = messages!!) }
    }

    // Метод для отправки сообщений в кластер
    @Throws(Exception::class)
    fun sendMessage(message: String?) {
        val mesg = Message(
            user?.firstName ?: "Не известный", message!!,
            user?.numberVagon ?: -1, user!!.address
        )
        val msg: org.jgroups.Message = org.jgroups.Message(null, mesg)
        Log.d(
            TAG,
            "Сообщений отправилось $message, " +
                    "\n имя: ${user!!.firstName} " +
                    "\n фамилия ${user!!.surname} " +
                    "\n отчество ${user!!.patronymic} " +
                    "\n UUID ${user!!.address}"
        )
        channel!!.send(msg)
        viewModelScope.launch {
            db?.messageDao()?.insert(msg.getObject())
        }
    }

    // Метод для обработки входящих сообщений
    override fun receive(msg: org.jgroups.Message) {
        //Log.d(TAG, msg.getObject<Message>().textMessage)
        //messageRecive = messageRecive + msg.getObject<Message>()
        if (context != null) {
            viewModelScope.launch {
                if (msg.getObject<Message>().userAddress != user!!.address) {
                    db?.messageDao()?.insert(msg.getObject())
                }
                val tempListMessage = db?.messageDao()?.getMessages()
                _uiState.update { newState -> newState.copy(messages = tempListMessage!!) }
            }
        }
    }


    override fun viewAccepted(newView: View) {
        Log.d(
            ContentValues.TAG,
            "-- Кластер состоит из " + newView.size() + " участников: " + newView + " --"
        )
    }

    fun getUserLogin(): Boolean {
        return user?.firstName != null
    }
}
Сделай так что бы сообщения отображались через библиотеку Paginator 3 (интегрируй  Paginator 3 в код)