package club.clubk.ktag.apps.konfigurator

import club.clubk.ktag.apps.core.ble.Packet
import java.util.UUID

data class Device(val uuid: UUID = UUID.randomUUID(),
                  var name: String = "Unknown Device",
                  var address: String = "FF:FF:FF:FF:FF:FF",
                  var deviceType : Int? = null,
                  var team : Int? = null,
                  var broadcastedTeam: Int? = null,
                  var playerID : Int? = null,
                  var deviceState: DeviceState? = null,
                  var systemkMajorVersion: Int? = null,
                  var systemkMinorVersion: Int? = null,
                  var maxHealth: Int? = null,
                  var broadcastedMaxHealth: Int? = null,
                  var specialWeaponsOnReentry: Int? = null,
                  var broadcastedSpecialWeaponsOnReentry: Int? = null
    ) {

    fun deviceTypeName(): String {
        return Packet.getDeviceTypeName(deviceType ?: -1)
    }

    /** True when every configured parameter has been acknowledged by the device. */
    fun allSettingsMatch(): Boolean =
        paramMatches(team, broadcastedTeam) &&
        paramMatches(maxHealth, broadcastedMaxHealth) &&
        paramMatches(specialWeaponsOnReentry, broadcastedSpecialWeaponsOnReentry)

    fun isOutdatedSystemK(): Boolean {
        val major = systemkMajorVersion ?: return false
        val minor = systemkMinorVersion ?: return false
        return major < MinSystemKVersion.MAJOR || (major == MinSystemKVersion.MAJOR && minor < MinSystemKVersion.MINOR)
    }

    fun SystemKVersionString(): String {
        val major = systemkMajorVersion ?: return "Unknown"
        val minor = systemkMinorVersion ?: return "Unknown"
        return "$major.${minor.toString().padStart(2, '0')}"
    }
}

/** A device parameter matches when it has been acknowledged and equals the desired value. */
private fun paramMatches(desired: Int?, broadcasted: Int?) = broadcasted != null && desired == broadcasted
