package net.buzzert.kordophone.backend.db.model

import android.view.Display.Mode
import io.realm.kotlin.Realm
import io.realm.kotlin.ext.realmListOf
import io.realm.kotlin.ext.toRealmList
import io.realm.kotlin.types.EmbeddedRealmObject
import io.realm.kotlin.types.RealmInstant
import io.realm.kotlin.types.RealmList
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.PrimaryKey
import net.buzzert.kordophone.backend.db.model.Conversation
import net.buzzert.kordophone.backend.model.GUID
import org.mongodb.kbson.ObjectId
import net.buzzert.kordophone.backend.model.Message as ModelMessage
import net.buzzert.kordophone.backend.model.Conversation as ModelConversation
import java.util.Date

open class Message(
    @PrimaryKey
    var guid: GUID,

    var text: String,
    var sender: String?,
    var date: RealmInstant,
    var attachmentGUIDs: RealmList<String>,

    var conversationGUID: GUID,
): RealmObject
{
    constructor() : this(
        guid = ObjectId().toString(),
        text = "",
        sender = null,
        date = RealmInstant.now(),
        attachmentGUIDs = realmListOf<String>(),
        conversationGUID = ObjectId().toString(),
    )

    fun toMessage(parentConversation: ModelConversation): ModelMessage {
        return ModelMessage(
            text = text,
            guid = guid,
            sender = sender,
            date = Date.from(date.toInstant()),
            attachmentGUIDs = attachmentGUIDs.toList(),
            conversation = parentConversation,
        )
    }
}

fun ModelMessage.toDatabaseMessage(outgoing: Boolean = false): Message {
    val from = this
    return Message().apply {
        text = from.text
        guid = from.guid
        sender = from.sender
        date = from.date.toInstant().toRealmInstant()
        conversationGUID = from.conversation.guid
        from.attachmentGUIDs?.let {
            attachmentGUIDs = it.toRealmList()
        }
    }
}
