package de.kif.common.model

import de.kif.common.SearchElement
import kotlinx.serialization.Serializable
import kotlin.random.Random

@Serializable
data class Post(
    override val id: Long? = null,
    val name: String,
    val content: String,
    val url: String,
    val image: String?,
    val pinned: Boolean,
    val hideOnProjector: Boolean,
    override val createdAt: Long = 0,
    override val updateAt: Long = 0
) : Model {

    override fun createSearch() = SearchElement(
        mapOf(
            "name" to name
        )
    )

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || this::class != other::class) return false

        other as Post

        if (id != other.id) return false
        if (name != other.name) return false
        if (content != other.content) return false
        if (url != other.url) return false
        if (image != other.image) return false
        if (pinned != other.pinned) return false
        if (hideOnProjector != other.hideOnProjector) return false

        return true
    }

    fun equalsIgnoreId(other: Post): Boolean = copy(id = null) == other.copy(id = null)

    override fun hashCode(): Int {
        var result = id?.hashCode() ?: 0
        result = 31 * result + name.hashCode()
        result = 31 * result + content.hashCode()
        result = 31 * result + url.hashCode()
        result = 31 * result + (image?.hashCode() ?: 0)
        result = 31 * result + pinned.hashCode()
        result = 31 * result + hideOnProjector.hashCode()
        return result
    }


    companion object {
        private const val chars = "abcdefghijklmnopqrstuvwxyz"
        private const val length = 32

        fun generateUrl() = (0 until length).asSequence()
            .map { Random.nextInt(chars.length) }
            .map { chars[it] }
            .map {
                if (Random.nextBoolean()) it else it.toUpperCase()
            }.joinToString("")
    }
}
