//
//  ForecastViewModel.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 10.03.2021.
//

import UIKit

protocol ForecastViewModelDelegate:ViewModelDelegate {
    func selectedWeatherDidChange()
}

class ForecastViewModel: ViewModelProtocol {
    //Public
    public let offsetHolder = TimePeriodOffsetHolder()
    public weak var delegate:ForecastViewModelDelegate?
    public private(set) var location: Location?
    public private(set) var selectedDailyWeather:DailyWeather?
    public private(set) var selectedHourlyWeather:HourlyWeather?
    public var selectedDailyWeatherIndex:Int {
        guard let loc = self.location else { return -1 }
        
        for (index, day) in loc.daily.enumerated() {
            if day == selectedDailyWeather {
                return index
            }
        }
        
        return -1
    }
    
    //Private
    private var locationManager: LocationManager
    
    deinit {
        self.locationManager.remove(delegate: self)
    }
    
    public init(locationManager: LocationManager) {
        self.locationManager = locationManager
        locationManager.add(delegate: self)
    }
    
    public func updateWeather() {
        locationManager.updateWeather()
    }
    
    public func selectDailyWeatherAt(index:Int) {
        guard let daily = location?.daily else { return }
        daily.enumerated().forEach {
            if $0 == index {
                self.selectedDailyWeather = $1
            }
        }
        self.delegate?.selectedWeatherDidChange()
    }
    
    public func selectHourlyWeatherAt(index:Int ) {
        guard let hourly = location?.hourly else { return }
        hourly.enumerated().forEach {
            if $0 == index {
                self.selectedHourlyWeather = $1
            }
        }
        self.delegate?.selectedWeatherDidChange()
    }
}

//MARK:- LocationManager Delegate
extension ForecastViewModel: LocationManagerDelegate {
    func locationManager(_ locationManager: LocationManager, changedCurrentLocation newLocation: Location?) {
        DispatchQueue.main.async {
            print("TVM-Forecast")
            self.location = newLocation
            self.selectDailyWeatherAt(index: 0)
            self.selectHourlyWeatherAt(index: 0)
            self.delegate?.viewModelDidChange(model: self)
        }
    }
}
