import SwiftUI
import Charts

struct TemperatureHistoryChart: View {

    @Binding
    var points: [TemperatureMeasurement]

    let upperTempLimit = 40.0
    let lowerTempLimit = -20.0

    let pastDateLimit = -3600
    let futureDateLimit = 0

    var body: some View {
        Chart {
            ForEach(points) { point in
                if let s = point.sensor0.optionalValue {
                    LineMark(
                        x: .value("Date", point.secondsToNow),
                        y: .value("Temperature", s))
                    .foregroundStyle(Color.red)
                }
                if let s = point.sensor1.optionalValue {
                    LineMark(
                        x: .value("Date", point.secondsToNow),
                        y: .value("Temperature", s))
                    .foregroundStyle(by: .value("Type", "Sensor 1"))
                }
            }
        }
        .chartXScale(domain: pastDateLimit...futureDateLimit)
        .chartYScale(domain: lowerTempLimit...upperTempLimit)
        .chartXAxis(.hidden)
        .chartLegend(.hidden)
        .chartYAxis {
            AxisMarks(position: .trailing, values: .stride(by: 10)) { value in
                AxisValueLabel(multiLabelAlignment: .trailing) {
                    if let intValue = value.as(Int.self) {
                        Text("\(intValue)°")
                            .font(.system(size: 10))
                            .foregroundColor(.white)
                    }
                }
              }
        }
        .padding()
    }
}

struct TemperatureHistoryChart_Previews: PreviewProvider {
    static var previews: some View {
        TemperatureHistoryChart(
            points: .constant(TemperatureMeasurement.mockData))
        .previewLayout(.fixed(width: 350, height: 150))
        .background(.gray)
    }
}
