//
//  GMCityManager.swift
//  Gengmei
//
//  Created by wangyang on 2018/4/7.
//  Copyright © 2018年 更美互动信息科技有限公司. All rights reserved.
//

import Foundation

@objcMembers
class GMCityManager: NSObject {
    private static let kCurrentCity = "currentCity"
    private static let kChinaRecentCitiesKey = "kChinaRecentCitiesKey"
    private static let kForeignRecentCitiesKey = "kForeignRecentCitiesKey"
    // MARK: - 当前城市
    static var isCitySet: Bool {
        let city = GMCache.fetchObject(atDocumentPathWithkey: kCurrentCity) as? WMCityObject
        if city != nil {
            return true
        } else {
            return false
        }
    }
    
    static var currentCity: WMCityObject {
        get {
            if let city = GMCache.fetchObject(atDocumentPathWithkey: kCurrentCity) as? WMCityObject {
                return city
            } else {
                let nationWideCity = WMCityObject()
                nationWideCity.name = "全部城市"
                nationWideCity.id = "worldwide"
                return nationWideCity
            }
        }
        set {
            GMCache.storeObject(atDocumentPathWithkey: kCurrentCity, object: newValue)
        }
    }

    static func add(recentCity: WMCityObject, with key: String) {
        if let recentCities = GMCache.fetchObject(atDocumentPathWithkey: key) as? [WMCityObject] {
            // 删除掉重复的
            var cities = recentCities.filter { recentCity.id != $0.id }

            // 把最新的放在0位置
            if recentCity.name != "全部城市" {
                cities.insert(recentCity, at: 0)
            }

            // 如果超过3个，删除最老的
            if cities.count > 3 {
                cities.removeLast()
            }
            GMCache.storeObject(atDocumentPathWithkey: key, object: cities as NSArray)
        } else {
            GMCache.storeObject(atDocumentPathWithkey: key, object: [recentCity] as NSArray)
        }
    }
    @objc(addChinaRecentCity:)
    static func add(chinaRecentCity: WMCityObject) {
        GMCityManager.add(recentCity: chinaRecentCity, with: kChinaRecentCitiesKey)
    }

    @objc(addForeignRecentCity:)
    static func add(foreignRecentCity: WMCityObject) {
        GMCityManager.add(recentCity: foreignRecentCity, with: kForeignRecentCitiesKey)
    }

    static var chinaRecentCities: [WMCityObject] {
        if let recentCities = GMCache.fetchObject(atDocumentPathWithkey: kChinaRecentCitiesKey) as? [WMCityObject] {
            return recentCities
        } else {
            return []
        }
    }

    static var foreignRecentCities: [WMCityObject] {
        if let recentCities = GMCache.fetchObject(atDocumentPathWithkey: kForeignRecentCitiesKey) as? [WMCityObject] {
            return recentCities
        } else {
            return []
        }
    }
}

