//
//  WdtHourlySummariesArray.swift
//  iOS_Test_App_2
//
//  Created by Demid Merzlyakov on 03.03.2021.
//  Copyright © 2021 Dynamix Software. All rights reserved.
//

import Foundation

/// Needed for XMLCoder to decode the array with the right key name
struct WdtHourlySummariesArray: Codable {
    private static let dateFormatter:DateFormatter = {
        let fmt = DateFormatter()
        fmt.timeZone = TimeZone(abbreviation: "PST")
        fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        return fmt
    }()
    let items: [WdtHourlySummary]
    
    private enum CodingKeys: String, CodingKey {
        /// This is actually a key that will be used for hourly_summaries individual elements.
        case items = "hourly_summary"
    }
    
    init(from decoder: Decoder) throws {
        func validate(dateString:String) -> Bool {
            let result = WdtHourlySummariesArray.dateFormatter.date(from: dateString)
            if result == nil {
                print("[WdtHourly] Could't validate date: \(dateString)")
            }
            return result != nil
        }
        
        let container = try decoder.container(keyedBy: CodingKeys.self)
        var rawItems = try container.decode([WdtHourlySummary].self, forKey: .items)
        rawItems = (rawItems.filter{ validate(dateString: $0.dateTimeLocal) })
        self.items = rawItems
    }
    
    func toAppModel(timeZone: TimeZone, updatedAt: Date) throws -> [HourlyWeather] {
        var result = [HourlyWeather]()
        for item in items {
            if let appModel = item.toAppModel(timeZone: timeZone, updatedAt: updatedAt) {
                result.append(appModel)
            }
        }
        return result
    }
}
