//
//  WdtDailySummariesArray.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 WdtDailySummariesArray: Codable {
    private static let dateFormatter:DateFormatter = {
        let fmt = DateFormatter()
        fmt.timeZone = TimeZone(abbreviation: "PST")
        fmt.dateFormat = "MM/dd/yyyy"
        
        return fmt
    }()
    let items: [WdtDailySummary]
    
    private enum CodingKeys: String, CodingKey {
        /// This is actually a key that will be used for daily_summaries individual elements.
        case items = "daily_summary"
    }
    
    init(from decoder: Decoder) throws {
        func validate(dateString:String) -> Bool {
            return WdtDailySummariesArray.dateFormatter.date(from: dateString) != nil
        }
        
        let container = try decoder.container(keyedBy: CodingKeys.self)
        var rawItems = try container.decode([WdtDailySummary].self, forKey: .items)
        rawItems = (rawItems.filter{ validate(dateString: $0.dateLocal) })
        self.items = rawItems
    }
    
    func toAppModel(timeZone: TimeZone, updatedAt: Date) throws -> [DailyWeather] {
        var result = [DailyWeather]()
        for item in items {
            if let appModel = item.toAppModel(timeZone: timeZone, updatedAt: updatedAt) {
                result.append(appModel)
            }
        }
        return result
    }
}
