package net.buzzert.kordophone.backend.model

import com.google.gson.annotations.SerializedName
import java.util.Date
import java.util.UUID

typealias GUID = String

data class Conversation(
    @SerializedName("guid")
    val guid: GUID,

    @SerializedName("date")
    var date: Date,

    @SerializedName("participantDisplayNames")
    var participants: List<String>,

    @SerializedName("displayName")
    var displayName: String?,

    @SerializedName("unreadCount")
    var unreadCount: Int,

    @SerializedName("lastMessagePreview")
    var lastMessagePreview: String?,

    @SerializedName("lastMessage")
    var lastMessage: Message?,

    var lastFetchedMessageGUID: String?,
) {
    companion object {
        fun generate(): Conversation {
            return Conversation(
                guid = UUID.randomUUID().toString(),
                date = Date(),
                participants = listOf("foo@foo.com"),
                displayName = null,
                unreadCount =  0,
                lastMessagePreview = null,
                lastMessage = null,
                lastFetchedMessageGUID = null,
            )
        }
    }

    val isGroupChat: Boolean
        get() = participants.count() > 1

    fun formattedDisplayName(): String {
        return displayName ?: participants.joinToString(", ")
    }

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

        val o = other as Conversation
        return (
            guid == o.guid &&
            date == o.date &&
            participants == o.participants &&
            displayName == o.displayName &&
            unreadCount == o.unreadCount &&
            lastFetchedMessageGUID == o.lastFetchedMessageGUID
        )
    }

    override fun hashCode(): Int {
        var result = guid.hashCode()
        result = 31 * result + date.hashCode()
        result = 31 * result + participants.hashCode()
        result = 31 * result + (displayName?.hashCode() ?: 0)
        result = 31 * result + unreadCount
        result = 31 * result + (lastMessage?.hashCode() ?: 0)
        result = 31 * result + (lastFetchedMessageGUID?.hashCode() ?: 0)
        return result
    }
}
