import SwiftUI
import Charts

struct TemperatureDayOverview: View {

    let points: [TemperatureMeasurement]

    init(points: [TemperatureMeasurement]) {
        self.points = points
    }
    
    init(storage: PersistentStorage, dateIndex: Int) {
        let points = storage.loadMeasurements(for: dateIndex)
        self.points = points
        update()
    }
    
    mutating func update() {
        self.upperTempLimit = max(40, points.maximumValue() ?? 40)
        self.lowerTempLimit = min(-20, points.minimumValue() ?? -20)
        let startDay = points.first?.date.dateIndex ?? Date().dateIndex
        self.pastDateLimit = Date(dateIndex: startDay)
        let endDay = (points.last?.date.dateIndex ?? Date().dateIndex) + 1
        self.futureDateLimit = Date(dateIndex: endDay)
    }
    
    var upperTempLimit: Double = 40.0
    var lowerTempLimit: Double = -20

    var pastDateLimit: Date = Date().startOfDay
    var futureDateLimit: Date = Date().startOfNextDay
    
    var body: some View {
        Chart {
            ForEach(points) { point in
                if let s = point.sensor0.optionalValue {
                    LineMark(
                        x: .value("Date", point.date),
                        y: .value("Temperature", s))
                    .foregroundStyle(by: .value("Type", "Sensor 0"))
                }
                if let s = point.sensor1.optionalValue {
                    LineMark(
                        x: .value("Date", point.date),
                        y: .value("Temperature", s))
                    .foregroundStyle(by: .value("Type", "Sensor 1"))
                }
            }
        }
        .aspectRatio(1, contentMode: .fit)
        //.chartXScale(domain: pastDateLimit...futureDateLimit)
        .chartYScale(domain: lowerTempLimit...upperTempLimit)
        .chartXAxis {
            AxisMarks(preset: .automatic)
            AxisMarks.init(values: AxisMarkValues.stride(by: .hour)) {
                AxisGridLine()
            }
        }
        .chartYAxis {
            AxisMarks(position: .trailing, values: .automatic) { value in
                AxisValueLabel(multiLabelAlignment: .trailing) {
                    if let intValue = value.as(Int.self) {
                        Text("\(intValue)°")
                            .font(.system(size: 10))
                            //.foregroundColor(.white)
                    }
                }
            }
            
            AxisMarks.init(values: AxisMarkValues.stride(by: 5)) {
                AxisGridLine()
            }
        }
    }
}

struct TemperatureDayOverview_Previews: PreviewProvider {
    static var previews: some View {
        TemperatureDayOverview(storage: PersistentStorage.mock, dateIndex: Date().dateIndex)
            .previewLayout(.fixed(width: 350, height: 150))
            //.background(.gray)
    }
}
