//
//  WdtLocation.swift
//  1Weather
//
//  Created by Demid Merzlyakov on 25.02.2021.
//

import Foundation
import CoreLocation

struct WdtLocation: Codable {
    public private (set) var lat: String?
    public private (set) var lon: String?
    public private (set) var city: String?
    public private (set) var region: String?
    public private (set) var country: String?
    public private (set) var zipcode: String?
    
    public var surfaceObservation: WdtSurfaceObservation
    public var dailySummaries: WdtDailySummariesArray?
    public var hourlySummaries: WdtHourlySummariesArray?
    
    private enum CodingKeys: String, CodingKey {
        case lat
        case lon
        case city
        case region
        case country
        case zipcode
        case surfaceObservation = "sfc_ob"
        case dailySummaries = "daily_summaries"
        case hourlySummaries = "hourly_summaries"
    }
    
    public func toAppModel(timeZone: TimeZone, updatedAt: Date) throws -> Location {
        var coordinates: CLLocationCoordinate2D? = nil
        if let lat = CLLocationDegrees(lat ?? ""), let lon = CLLocationDegrees(lon ?? "") {
            coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lon)
        }
        var today = surfaceObservation.toAppModel(timeZone: timeZone, updatedAt: updatedAt)
        let dailyWeather = try dailySummaries?.toAppModel(timeZone: timeZone, updatedAt: updatedAt) ?? [DailyWeather]()
        let hourlyWeather = try hourlySummaries?.toAppModel(timeZone: timeZone, updatedAt: updatedAt) ?? [HourlyWeather]()
        
        if let firstDay = dailyWeather.first {
            today?.minTemp = firstDay.minTemp
            today?.maxTemp = firstDay.maxTemp
            today?.precipitationProbability = firstDay.precipitationProbability
            today?.sunState = firstDay.sunState
            today?.moonState = firstDay.moonState
            today?.moonPhase = firstDay.moonPhase
        }
        
        return Location(lastTimeUpdated: updatedAt,
                        coordinates: coordinates,
                        imageName: nil,
                        countryCode: nil,
                        countryName: country,
                        region: region,
                        cityName: city,
                        nickname: nil,
                        zip: zipcode,
                        fipsCode: nil,
                        timeZone: timeZone,
                        today: today,
                        daily: dailyWeather,
                        hourly: hourlyWeather)
    }
}
