package io.nexilis.service.data.viewmodels

import android.content.Context
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import io.nexilis.service.core.getFileName
import io.nexilis.service.core.getMimeType
import io.nexilis.service.core.toFile
import io.nexilis.service.data.daos.MessageStatusDao
import io.nexilis.service.data.entities.Message
import io.nexilis.service.data.repositories.MessageRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MessageViewModel @Inject constructor(
    private val repository: MessageRepository,
    private val messageStatusDao: MessageStatusDao
) :
    ViewModel() {

    val all: LiveData<List<Message>> = repository.all

    fun get(id: String): LiveData<Message> {
        return repository.get(id)
    }

    fun getOpposite(pin: String): LiveData<List<Message>> {
        return repository.getOpposite(pin)
    }

    fun insert(entity: Message) = viewModelScope.launch(Dispatchers.IO) {
        repository.insert(entity)
    }

    fun send(
        context: Context,
        entity: Message
    ) =
        viewModelScope.launch(Dispatchers.IO) {
            if (entity.uri != Uri.EMPTY) {
                context.contentResolver.openInputStream(entity.uri).use { input ->
                    input?.toFile(context, entity.uri.getFileName(context))
                }
                val mimeType = context.getMimeType(entity.uri)
                if (mimeType.startsWith("image")) {
                    entity.thumb_id = entity.uri.getFileName(context) ?: ""
                    entity.image_id = entity.thumb_id
                } else if (mimeType.startsWith("audio")) {
                    entity.audio_id = entity.uri.getFileName(context) ?: ""
                } else if (mimeType.startsWith("video")) {
                    entity.video_id = entity.uri.getFileName(context) ?: ""
                } else {
                    entity.file_id = entity.uri.getFileName(context) ?: ""
                }
            }
            repository.send(context, entity) { id, pin, status ->
                viewModelScope.launch(Dispatchers.IO) {
                    messageStatusDao.updateStatus(
                        status,
                        messageId = id,
                        pin = pin
                    )
                }
            }
        }

}