package club.clubk.ktag.apps.core

import androidx.compose.ui.graphics.Color

/**
 * Unified data class representing a KTag device.
 * Superset of fields used by the subapps.
 */
data class DeviceModel(
    val name: String,
    val version: String = "",
    val deviceType: String = "",
    val id: Int = 0,
    val image: Int = 0,
    val bleAddress: String = "00:00:00:00:00:00",
    val rssi: Int = -128,
    val color: Color = Color.Companion.White,
    val teamId: Byte = NO_TEAMS,
    val health: Int = 0,
    val inRange: Boolean = false,
    val hasBeenTagged: Boolean = false,
    val isTaggedOut: Boolean = false,
    val timeToLiveMs: Int = DEFAULT_TTL_MS
) {
    fun withResetTtl(ttlMs: Int = DEFAULT_TTL_MS): DeviceModel = copy(timeToLiveMs = ttlMs)

    fun withDecrementedTtl(decrementMs: Int): DeviceModel =
        copy(timeToLiveMs = timeToLiveMs - decrementMs)

    fun withRssi(newRssi: Int, minRssi: Int): DeviceModel =
        copy(rssi = newRssi, inRange = newRssi >= minRssi)

    fun withTagged(): DeviceModel = copy(hasBeenTagged = true)

    fun withTaggedOut(ttlMs: Int = TAGGED_DISPLAY_TTL_MS): DeviceModel = copy(isTaggedOut = true, timeToLiveMs = ttlMs)

    fun withReset(): DeviceModel = copy(hasBeenTagged = false)

    val isExpired: Boolean
        get() = timeToLiveMs <= 0

    companion object {
        const val DEFAULT_TTL_MS = 5000
        const val TAGGED_DISPLAY_TTL_MS = 5000

        const val ALL_TEAMS: Byte = 0
        const val RED_TEAM: Byte = 1
        const val BLUE_TEAM: Byte = 2
        const val NO_TEAMS: Byte = 3

        fun getTeamCounts(contacts: List<DeviceModel>): TeamCounts {
            var redCount = 0
            var blueCount = 0

            for (contact in contacts) {
                when (contact.teamId) {
                    RED_TEAM -> redCount++
                    BLUE_TEAM -> blueCount++
                }
            }

            return TeamCounts(redCount, blueCount)
        }
    }
}

/**
 * Data class holding team member counts.
 */
data class TeamCounts(
    val red: Int,
    val blue: Int
)