//
//  CountryCode.swift
//  SendFax
//
//  Created by Ronak Kalavadia on 24/05/18.
//  Copyright © 2018 FaxApp. All rights reserved.
//

import UIKit


struct Country {
    var code: String?
    var name: String?
    var phoneCode: String?
    var flag: UIImage? {
        guard let code = self.code else { return nil }
        return UIImage(named: code.uppercased())
    }
    
    init(code: String?, name: String?, phoneCode: String?) {
        self.code = code
        self.name = name
        self.phoneCode = phoneCode
    }
}



class CountryCode: NSObject {
    
    static func countryNamesByCode() -> [Country] {
        var countries = [Country]()
        let bundle = Bundle(for: CountryCode().classForCoder)
        guard let jsonPath = bundle.path(forResource: "countryCodes", ofType: "json"), let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else {
            return countries
        }
        
        do {
            if let jsonObjects = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? NSArray {
                
                var currentCountryCode: String = ""
                if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
                    currentCountryCode = countryCode
                }
                
                for jsonObject in jsonObjects {
                    
                    guard let countryObj = jsonObject as? NSDictionary else {
                        return countries
                    }
                    
                    guard let code = countryObj["code"] as? String, let phoneCode = countryObj["dial_code"] as? String, let name = countryObj["name"] as? String else {
                        return countries
                    }
                    
                    let country = Country(code: code, name: name, phoneCode: phoneCode)
                    if country.code == currentCountryCode{
                        countries.insert(country, at: 0)
                    }else{
                        countries.append(country)
                    }
                }
                
            }
        } catch {
            return countries
        }
        return countries
    }
    
}
