//
//  LocationManager.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 01.02.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import CoreLocation

class LocationManager : NSObject, CLLocationManagerDelegate {
    private let locationManager = CLLocationManager()
    
    var needGetUserCity = false
    
    internal override init() {
        super.init()
        locationManager.delegate = self
        if #available(iOS 8.0, *) {
            locationManager.requestWhenInUseAuthorization()
        }
        locationManager.startUpdatingLocation()
    }
    
    class func sharedInstance() -> LocationManager {
        struct Shared {
            static let sharedInstance = LocationManager()
        }
        return Shared.sharedInstance
    }
    
    var worked : Bool {
        //		TODO: worked method for understanding location manager
        return true
    }
    
    var currentCityId: Int?
    
    var currentLocation: CLLocationCoordinate2D? {
        set {
        }
        get {
            if currentCityId != NSUserDefaults.standardUserDefaults().integerForKey(UserDefaultsCity) {
                let newCityId = NSUserDefaults.standardUserDefaults().integerForKey(UserDefaultsCity)
                self.currentCityId = newCityId
                var cities = CitiesManager.sharedInstance().getCities()
                var currentCity: City?
                
                if let cityId = cities.indexOf({$0.id == newCityId}) {
                    currentCity = cities[cityId]
                }
                return currentCity?.location
            }
            return nil
        }
    }
    
    var location : CLLocation? {
        return locationManager.location
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if needGetUserCity {
            Facade.sharedInstance().getUserCity()
        }
    }
}

