import Foundation

struct CsvConverter {

    private let dateFormatter: DateFormatter

    init() {
        dateFormatter = .init()
        dateFormatter.dateStyle = .short
        dateFormatter.timeStyle = .medium
    }

    private var header: String {
        "Index;Date;Sensor 0;Sensor 1\n"
    }

    func convert(measurements: [TemperatureMeasurement]) -> String {
        header + measurements.enumerated().map { (index, measurement) -> String in
            let parts: [String] = [
                "\(index)",
                dateFormatter.string(from: measurement.date),
                convert(measurement.sensor0),
                convert(measurement.sensor1)
            ]

            return parts.joined(separator: ";")
        }.joined(separator: "\n")
    }

    private func convert(_ value: TemperatureValue) -> String {
        switch value {
        case .notFound:
            return ""
        case .invalidMeasurement:
            return "?"
        case .value(let value):
            return String(format:"%.1f", value)
        }
    }
}
