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

import Foundation

class CitiesManager {
  private var _cities = [City]()
  
  class func sharedInstance() -> CitiesManager {
    struct Shared {
      static let sharedInstance = CitiesManager()
    }
    return Shared.sharedInstance
  }
  
  private init() {
    
  }
  
  func loadCities() {
    var path = NSSearchPathForDirectoriesInDomains(
      .DocumentDirectory,
      NSSearchPathDomainMask.UserDomainMask,
      true
      )[0] as String
    path += "/cities.plist"
    let citiesDictionary = NSArray(contentsOfFile: path)
    
    for i in 0 ..< citiesDictionary!.count {
      let dict = citiesDictionary![i] as! [String : AnyObject]
      _cities.append(City(dictionary: dict))
    }
  }
  
  func saveCities() {
    var path = NSSearchPathForDirectoriesInDomains(
      .DocumentDirectory,
      NSSearchPathDomainMask.UserDomainMask,
      true
      )[0] as String
    path += "/cities.plist"
    print(path)
    
    let citiesDictionaties = NSMutableArray()
    
    for city in _cities {
      let dict = city.getDictionary()
      citiesDictionaties.addObject(dict)
    }
    
    citiesDictionaties.writeToFile(path, atomically: true)
  }
  
  func setCities(cities : JSON) {
    _cities = [City]()
    
    for (_, subJson) in cities {
      _cities.append(City(json: subJson))
    }
  }
  
  func getCities() -> [City] {
    return _cities
  }
  
  func userCity() -> City {
    let cityId = NSUserDefaults.standardUserDefaults().integerForKey(UserDefaultsCity)
    return _cities.filter { $0.id == cityId }[0]
  }
  
  func setUserCity(city: City) {
    let cityId = city.id
    NSUserDefaults.standardUserDefaults().setInteger(cityId, forKey: UserDefaultsCity)
  }
}
