package com.drivervault.phoneapp.car

import androidx.car.app.CarContext
import androidx.car.app.model.ItemList
import androidx.car.app.model.ListTemplate
import androidx.car.app.model.Row
import androidx.car.app.model.Template

/** A car and the badge its service history earns it. */
data class GarageEntry(val car: VaultCar, val status: CarStatus)

/**
 * The garage as a head unit can hold it: one row per car, its due badge on the
 * second line, worst first.
 *
 * Worst first rather than the phone's own order, because the host will show only
 * the first few rows of any list — and the car this list exists to mention is the
 * overdue one, not whichever was added first.
 */
class GarageScreen(carContext: CarContext) : VaultScreen<List<GarageEntry>>(carContext) {

    override val title: String get() = strings.t("dashboard.title")
    override val isRoot: Boolean get() = true

    override fun read(api: VaultApi): List<GarageEntry> =
        api.cars()
            .map { car ->
                // One car's history failing shouldn't cost the whole garage its
                // list; that car simply has no badge to show.
                val latest = runCatching { api.latestService(car.id) }.getOrNull()
                GarageEntry(car, format.serviceStatus(latest, car.currentKm))
            }
            .sortedByDescending { it.status.key.severity }

    override fun template(data: List<GarageEntry>): Template {
        val list = ItemList.Builder().setNoItemsMessage(strings.t("dashboard.empty"))
        for (entry in data.take(listLimit())) {
            list.addItem(row(entry))
        }
        return ListTemplate.Builder()
            .setTitle(title)
            .setHeaderAction(headerAction)
            .setActionStrip(refreshStrip)
            .setSingleList(list.build())
            .build()
    }

    private fun row(entry: GarageEntry): Row {
        val subtitle = listOfNotNull(
            entry.car.subtitle.takeIf { it.isNotEmpty() },
            // Which of these cars are somebody else's is worth a head unit's
            // second line; the phone flies the same chip.
            when {
                entry.car.isOwner -> null
                entry.car.isReadOnly -> strings.t("dashboard.sharedReadOnly")
                else -> strings.t("dashboard.shared")
            },
        ).joinToString(" · ")

        return Row.Builder()
            .setTitle(entry.car.name)
            .apply { if (subtitle.isNotEmpty()) addText(subtitle) }
            .addText(tinted(entry.status))
            .setBrowsable(true)
            .setOnClickListener {
                screenManager.push(CarDueScreen(carContext, entry.car))
            }
            .build()
    }
}
