<commit_before>//
//  JUWCollectionCenterManager.swift
//  Ajuda
//
//  Created by <NAME> on 9/21/17.
//  Copyright © 2017 <NAME>. All rights reserved.
//

import UIKit
import RealmSwift

class JUWCollectionCenterManager: NSObject {

    private let networkManager = JUWNetworkManager()
    
    func getCollectionCenters(centers: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
        networkManager.get(url: kCollectionCentersUrl, completion: { (result) in
            DispatchQueue.global().async {
                if let array = result as? [Any] {
                    let realm = try! Realm()

                    for value in array {
                        if let dictionary = value as? [String: Any] {
                            let predicate = NSPredicate(format: "centerIdentifier = %@", dictionary["id"] as! String)
                            var center = realm.objects(JUWCollectionCenter.self).filter(predicate).first
                            if center == nil {
                                center = JUWCollectionCenter()
                                try! realm.write {
                                    realm.add(center!)
                                }
                            }
                            try! realm.write {
                                if let name = dictionary["nombre"] as? String {
                                    center?.name = name
                                }

                                if let address = dictionary["direccion"] as? String {
                                    center?.address = address
                                }
                                
                                if let identifier = dictionary["id"] as? String {
                                    center?.centerIdentifier = identifier
                                }

                                if let geoPosDictionary = dictionary["geopos"] as? [String: Any] {
                                    if geoPosDictionary.count > 0 {
                                        if let latitude = geoPosDictionary["lat"] as? Double {
                                            center?.latitude = latitude
                                        }
                                        if let longitude = geoPosDictionary["lng"] as? Double {
                                            center?.longitude = longitude
                                        }
                                    }
                                }
                            }
                        }
                    }
                    DispatchQueue.main.async {
                        centers()
                    }
                }
            }
        }) { (error) in
            failure(error!)
        }
    }
    
    func collectionCenters(whichNeed product: String, completion: @escaping (_ result: [JUWCollectionCenter]) -> Void) {
        let query = product.lowercased().stripCharacters(in: CharacterSet.alphanumerics.inverted)
        precondition(!query.isEmpty, "Query should not be an empty")
        
        var collectionCenter: [JUWCollectionCenter] = []
        guard let url = String(format: kCollectionCenterSearchProductUrl, query).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {
            completion(collectionCenter)
            return
        }
        networkManager.get(url: url, completion: { (result) in
            
            if let array = result as? [Any] {
                let realm = try! Realm()
                
                for value in array {
                    if let dictionary = value as? [String: Any] {
                        
                        let predicate = NSPredicate(format: "centerIdentifier = %@", dictionary["acopioId"] as! String)
                        if let center = realm.objects(JUWCollectionCenter.self).filter(predicate).first {
                            collectionCenter.append(center)
                        }
                    }
                }
            }
            completion(collectionCenter)
        }) { (error) in
            completion(collectionCenter)
        }
    }
}

extension String {
    func stripCharacters(in set: CharacterSet) -> String {
        return self.components(separatedBy: set).joined(separator: "")
    }
}<commit_msg>Excute results in main queue<commit_after>//
//  JUWCollectionCenterManager.swift
//  Ajuda
//
//  Created by <NAME> on 9/21/17.
//  Copyright © 2017 <NAME>. All rights reserved.
//

import UIKit
import RealmSwift

class JUWCollectionCenterManager: NSObject {

    private let networkManager = JUWNetworkManager()
    
    func getCollectionCenters(centers: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
        networkManager.get(url: kCollectionCentersUrl, completion: { (result) in
            DispatchQueue.global().async {
                if let array = result as? [Any] {
                    let realm = try! Realm()

                    for value in array {
                        if let dictionary = value as? [String: Any] {
                            let predicate = NSPredicate(format: "centerIdentifier = %@", dictionary["id"] as! String)
                            var center = realm.objects(JUWCollectionCenter.self).filter(predicate).first
                            if center == nil {
                                center = JUWCollectionCenter()
                                try! realm.write {
                                    realm.add(center!)
                                }
                            }
                            try! realm.write {
                                if let name = dictionary["nombre"] as? String {
                                    center?.name = name
                                }

                                if let address = dictionary["direccion"] as? String {
                                    center?.address = address
                                }
                                
                                if let identifier = dictionary["id"] as? String {
                                    center?.centerIdentifier = identifier
                                }

                                if let geoPosDictionary = dictionary["geopos"] as? [String: Any] {
                                    if geoPosDictionary.count > 0 {
                                        if let latitude = geoPosDictionary["lat"] as? Double {
                                            center?.latitude = latitude
                                        }
                                        if let longitude = geoPosDictionary["lng"] as? Double {
                                            center?.longitude = longitude
                                        }
                                    }
                                }
                            }
                        }
                    }
                    DispatchQueue.main.async {
                        centers()
                    }
                }
            }
        }) { (error) in
            failure(error!)
        }
    }
    
    func collectionCenters(whichNeed product: String, completion: @escaping (_ result: [JUWCollectionCenter]) -> Void) {
        let query = product.lowercased().stripCharacters(in: CharacterSet.alphanumerics.inverted)
        precondition(!query.isEmpty, "Query should not be an empty")
        
        var collectionCenter: [JUWCollectionCenter] = []
        guard let url = String(format: kCollectionCenterSearchProductUrl, query).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {
            DispatchQueue.main.async {
                completion(collectionCenter)
            }
            return
        }
        networkManager.get(url: url, completion: { (result) in
            
            if let array = result as? [Any] {
                let realm = try! Realm()
                
                for value in array {
                    if let dictionary = value as? [String: Any] {
                        
                        let predicate = NSPredicate(format: "centerIdentifier = %@", dictionary["acopioId"] as! String)
                        if let center = realm.objects(JUWCollectionCenter.self).filter(predicate).first {
                            collectionCenter.append(center)
                        }
                    }
                }
            }
            DispatchQueue.main.async {
                completion(collectionCenter)
            }
        }) { (error) in
            DispatchQueue.main.async {
                completion(collectionCenter)
            }
        }
    }
}

extension String {
    func stripCharacters(in set: CharacterSet) -> String {
        return self.components(separatedBy: set).joined(separator: "")
    }
}
{'fraction_non_alphanumeric': 0.07998202651089643, 'fraction_numerical': 0.0022466861379465287, 'mean_word_length': 1.0599259602036095, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 40, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3423591', 'n_tokens_mistral': 2005, 'n_tokens_neox': 1851, 'n_words': 451}