//
//  SettingsDetailsViewModel.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 27.03.2021.
//

import UIKit
import Localize_Swift

class SettingsDetailsViewModel: ViewModelProtocol {
    //Public
    let rowType:SettingsRow
    weak var delegate:ViewModelDelegate?
    
    public var temperatures:[UnitTemperature] {
        return [.kelvin, .celsius, .fahrenheit]
    }
    public var winds:[UnitSpeed] {
        return [.metersPerSecond, .kilometersPerHour, .milesPerHour, .knots]
    }
    public var pressures:[UnitPressure] {
        return [.inchesOfMercury, .millibars, .millimetersOfMercury, .atmosphere,  .kilopascals]
    }
    public var distances:[UnitLength] {
        return [.miles, .kilometers]
    }
    public var languages:[String] {
        return Localize.availableLanguages()
    }
    
    //Selected
    public var selectedTemperatureIndex: Int {
        return temperatures.firstIndex{ $0 == Settings.shared.temperatureType } ?? -1
    }
    public var selectedWindIndex: Int {
        return winds.firstIndex{ $0 == Settings.shared.windSpeedType } ?? -1
    }
    public var selectedPressureIndex:Int {
        return pressures.firstIndex{ $0 == Settings.shared.pressureType } ?? -1
    }
    public var selectedDistanceIndex:Int {
        return distances.firstIndex{ $0 == Settings.shared.distanceType } ?? -1
    }
    public var selectedLanguageIndex:Int {
        return Localize.availableLanguages().firstIndex{ $0 == Localize.currentLanguage() } ?? -1
    }
    
    deinit {
        Settings.shared.delegate.remove(delegate: self)
    }
    
    init(rowType: SettingsRow) {
        self.rowType = rowType
        Settings.shared.delegate.add(delegate: self)
    }
    
    public func selectUnitAtIndex(index: Int) {
        switch rowType {
        case .temperature:
            Settings.shared.temperatureType = temperatures[index]
        case .wind:
            Settings.shared.windSpeedType = winds[index]
        case .pressure:
            Settings.shared.pressureType = pressures[index]
        case .distance:
            Settings.shared.distanceType = distances[index]
        default:
            break
        }
        
        delegate?.viewModelDidChange(model: self)
    }
    
    public func selectLanguage(identifier:String, atIndex index:Int) {
        
    }
}

//MARK:- SettingsDetails View Model
extension SettingsDetailsViewModel: SettingsDelegate {
    func settingsDidChange() {
        self.delegate?.viewModelDidChange(model: self)
    }
}
