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

import io.realm.kotlin.ext.realmListOf
import io.realm.kotlin.ext.toRealmList
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.model.GUID
import org.mongodb.kbson.ObjectId
import net.buzzert.kordophone.backend.model.Conversation as ModelConversation
import java.util.Date

open class Conversation(
    @PrimaryKey
    var guid: GUID,

    var displayName: String?,
    var participants: RealmList<String>,
    var date: RealmInstant,
    var unreadCount: Int,

    var lastMessageGUID: String?,
    var lastMessagePreview: String?,
): RealmObject
{
    constructor() : this(
        guid = ObjectId().toString(),

        displayName = null,
        participants = realmListOf<String>(),
        date = RealmInstant.now(),
        unreadCount = 0,
        lastMessagePreview = null,
        lastMessageGUID = null,
    )

    fun toConversation(): ModelConversation {
        return ModelConversation(
            displayName = displayName,
            participants = participants.toList(),
            date = Date.from(date.toInstant()),
            unreadCount = unreadCount,
            guid = guid,
            lastMessagePreview = lastMessagePreview,
            lastMessage = null,
            lastFetchedMessageGUID = lastMessageGUID
        )
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || javaClass != other.javaClass) return false

        val o = other as Conversation
        return guid == o.guid
    }

    override fun hashCode(): Int {
        return guid.hashCode()
    }
}

fun ModelConversation.toDatabaseConversation(): Conversation {
    val from = this
    return Conversation().apply {
        displayName = from.displayName
        participants = from.participants.toRealmList()
        date = from.date.toInstant().toRealmInstant()
        unreadCount = from.unreadCount
        lastMessagePreview = from.lastMessagePreview
        lastMessageGUID = from.lastFetchedMessageGUID
        guid = from.guid
    }
}

