import Foundation

struct RouteOverview {

    /// The total active energy in kcal
    let energy: Double

    /// The total distance of the track in meters
    let distance: Double

    /// The total duration in seconds
    let duration: TimeInterval

    /// The total ascended altitude in meters
    let ascendedElevation: Double

    let start: Date?

    let end: Date?

    static func combine(_ overviews: [RouteOverview]) -> RouteOverview {
        RouteOverview(
            energy: overviews.reduce(0) { $0 + $1.energy },
            distance: overviews.reduce(0) { $0 + $1.distance },
            duration: overviews.reduce(0) { $0 + $1.duration },
            ascendedElevation: overviews.reduce(0) { $0 + $1.ascendedElevation },
            start: overviews.compactMap { $0.start }.min(),
            end: overviews.compactMap { $0.end }.max())
    }

    var days: Int {
        guard let start, let end else {
            return 0
        }
        return start.inclusiveDays(to: end)
    }
}

extension RouteOverview {

    func update(labels: inout [ContentLabel], language: ContentLanguage) {
        let locale = language.locale
        let days = self.days

        if days != 1 {
            labels.insertOrReplace(icon: .calendar, value: language.text(days: days))
        } else {
            labels.insertOrReplace(icon: .statisticsTime, value: duration.duration(locale: locale))
        }
        labels.insertOrReplace(icon: .statisticsDistance, value: String(format: "%.1f km", locale: locale, distance / 1000))
        labels.insertOrReplace(icon: .statisticsElevationUp, value: ascendedElevation.length(roundingToNearest: 50))
        labels.insertOrReplace(icon: .statisticsEnergy, value: energy.energy(roundingToNearest: 50))
    }
}
