package de.kif.common.model

import de.kif.common.SearchElement
import kotlinx.serialization.Serializable

@Serializable
data class Schedule(
    override val id: Long?,
    val workGroup: WorkGroup,
    val room: Room,
    val day: Int,
    val time: Int,
    val lookRoom: Boolean,
    val lookTime: Boolean,
    override val createdAt: Long = 0,
    override val updateAt: Long = 0
) : Model {

    override fun createSearch() = SearchElement(
        mapOf(
            "workgroup" to workGroup.name,
            "room" to room.name,
            "track" to (workGroup.track?.name ?: ""),
            "language" to workGroup.language.localeName
        ), mapOf(), mapOf(
            "day" to day.toDouble()
        )
    )

    fun getAbsoluteStartTime(): Int = day * 60 * 24 + time
    fun getAbsoluteEndTime(): Int = getAbsoluteStartTime() + workGroup.length

    companion object {
        fun timeOfDayToString(time: Int): String {
            var day = time % (24 * 60)
            if (day < 0) day += 24 * 60

            val hour = day / 60
            val minute = day % 60

            return hour.toString().padStart(2, '0') + ":" + minute.toString().padStart(2, '0')
        }

        fun timeDifferenceToString(time: Long): String {
            if (time < 0) {
                return "running"
            }

            var remainder = time

            val seconds = (remainder % 60).toString().padStart(2, '0')
            remainder /= 60

            val minutes = (remainder % 60).toString().padStart(2, '0')
            remainder /= 60

            val hours = (remainder % 24).toString().padStart(2, '0')
            remainder /= 24

            val days = remainder

            if (days > 1) {
                return "$days days"
            }
            if (days > 0) {
                return "1 day"
            }

            if (hours == "00") {
                return "$minutes:$seconds"
            }

            return "$hours:$minutes:$seconds"
        }
    }
}
