<commit_before>//
//  EventAPI.swift
//  CoreDataCRUD
//
//  Copyright © 2016 <NAME>. All rights reserved.
//

import UIKit
import CoreData

/**
    Event API contains the endpoints to Create/Read/Update/Delete Events.
*/
class EventAPI {

    fileprivate let persistenceManager: PersistenceManager!
    fileprivate var mainContextInstance: NSManagedObjectContext!

    fileprivate let idNamespace = EventAttributes.eventId.rawValue
    fileprivate let fbURLNamespace = EventAttributes.fb_url.rawValue
    fileprivate let ticketURLNamespace = EventAttributes.ticket_url.rawValue
    fileprivate let titleNamespace = EventAttributes.title.rawValue
    fileprivate let dateNamespace = EventAttributes.date.rawValue
    fileprivate let cityNamespace = EventAttributes.city.rawValue
    fileprivate let venueNamespace = EventAttributes.venue.rawValue
    fileprivate let countryNamespace = EventAttributes.country.rawValue
    fileprivate let attendeesNamespace = EventAttributes.attendees.rawValue

    //Utilize Singleton pattern by instanciating EventAPI only once.
    class var sharedInstance: EventAPI {
        struct Singleton {
            static let instance = EventAPI()
        }

        return Singleton.instance
    }

    init() {
        self.persistenceManager = PersistenceManager.sharedInstance
        self.mainContextInstance = persistenceManager.getMainContextInstance()
    }

    // MARK: Create

    /**
        Create a single Event item, and persist it to Datastore via Worker(minion),
        that synchronizes with Main context.
    
        - Parameter eventDetails: <Dictionary<String, AnyObject> A single Event item to be persisted to the Datastore.
        - Returns: Void
    */
    func saveEvent(_ eventDetails: Dictionary<String, AnyObject>) {

        //Minion Context worker with Private Concurrency type.
        let minionManagedObjectContextWorker: NSManagedObjectContext =
        NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
        minionManagedObjectContextWorker.parent = self.mainContextInstance

        //Create new Object of Event entity
        let eventItem = NSEntityDescription.insertNewObject(forEntityName: EntityTypes.Event.rawValue,
            into: minionManagedObjectContextWorker) as! Event

        //Assign field values
        for (key, value) in eventDetails {
            for attribute in EventAttributes.getAll {
                if (key == attribute.rawValue) {
                    eventItem.setValue(value, forKey: key)
                }
            }
        }

        //Save current work on Minion workers
        self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)

        //Save and merge changes from Minion workers with Main context
        self.persistenceManager.mergeWithMainContext()

        //Post notification to update datasource of a given Viewcontroller/UITableView
        self.postUpdateNotification()
    }

    /**
        Create new Events from a given list, and persist it to Datastore via Worker(minion),
        that synchronizes with Main context.
    
        - Parameter eventsList: Array<AnyObject> Contains events to be persisted to the Datastore.
        - Returns: Void
    */
    func saveEventsList(_ eventsList: Array<AnyObject>) {
        DispatchQueue.global().async {

            //Minion Context worker with Private Concurrency type.
            let minionManagedObjectContextWorker: NSManagedObjectContext =
                NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
            minionManagedObjectContextWorker.parent = self.mainContextInstance

            //Create eventEntity, process member field values<commit_msg>Reformat code<commit_after>//
//  EventAPI.swift
//  CoreDataCRUD
//
//  Copyright © 2016 <NAME>. All rights reserved.
//

import UIKit
import CoreData

/**
    Event API contains the endpoints to Create/Read/Update/Delete Events.
*/
class EventAPI {

    fileprivate let persistenceManager: PersistenceManager!
    fileprivate var mainContextInstance: NSManagedObjectContext!

    fileprivate let idNamespace = EventAttributes.eventId.rawValue
    fileprivate let fbURLNamespace = EventAttributes.fb_url.rawValue
    fileprivate let ticketURLNamespace = EventAttributes.ticket_url.rawValue
    fileprivate let titleNamespace = EventAttributes.title.rawValue
    fileprivate let dateNamespace = EventAttributes.date.rawValue
    fileprivate let cityNamespace = EventAttributes.city.rawValue
    fileprivate let venueNamespace = EventAttributes.venue.rawValue
    fileprivate let countryNamespace = EventAttributes.country.rawValue
    fileprivate let attendeesNamespace = EventAttributes.attendees.rawValue

    //Utilize Singleton pattern by instanciating EventAPI only once.
    class var sharedInstance: EventAPI {
        struct Singleton {
            static let instance = EventAPI()
        }

        return Singleton.instance
    }

    init() {
        self.persistenceManager = PersistenceManager.sharedInstance
        self.mainContextInstance = persistenceManager.getMainContextInstance()
    }

    /**
     Retrieve an Event
     
     Scenario:
     Given that there there is only a single event in the datastore
     Let say we only created one event in the datastore, then this function will get that single persisted event
     Thus calling this method multiple times will result in getting always the same event.
     
     - Returns: a found Event item, or nil
     */
    func getSingleAndOnlyEvent(eventTitle: String) -> Event? {
        var fetchedResultEvent: Event?
        
        // Create request on Event entity
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: EntityTypes.Event.rawValue)
        
        //Execute Fetch request
        do {
            let fetchedResults = try  self.mainContextInstance.fetch(fetchRequest) as! [Event]
            fetchRequest.fetchLimit = 1
            
            if fetchedResults.count != 0 {
                fetchedResultEvent =  fetchedResults.first
            }
        } catch let fetchError as NSError {
            print("retrieve single event error: \(fetchError.localizedDescription)")
        }
        
        return fetchedResultEvent
    }
    
    // MARK: Create

    /**
        Create a single Event item, and persist it to Datastore via Worker(minion),
        that synchronizes with Main context.
    
        - Parameter eventDetails: <Dictionary<String, AnyObject> A single Event item to be persisted to the Datastore.
        - Returns: Void
    */
    func saveEvent(_ eventDetails: Dictionary<String, AnyObject>) {

        //Minion Context worker with Private Concurrency type.
        let minionManagedObjectContextWorker: NSManagedObjectContext =
        NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
        minionManagedObjectContextWorker.parent = self.mainContextInstance

        //Create new Object of Event entity
        let eventItem = NSEntityDescription.insertNewObject(forEntityName: EntityTypes.Event.rawValue,
            into: minionManagedObjectContextWorker) as! Event

        //Assign field values
        for (key, value) in eventDetails {
            for attribute in EventAttributes.getAll {
                if (key == attribute.rawValue) {
                    eventItem.setValue(value, forKey: key)
                }
            }
        }

        //Save current work on Minion workers
        self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)

        //Save and merge changes from Minion workers with Main context
        self.persistenceManager.mergeWithMainContext()

        //Post notification to update datasource of a given Viewcontroller/UITableView
        self.postUpdateNotification()
    }
    
    /**
     Create a single Event item, and persist it to Datastore via Worker(minion),
     that synchronizes with Main context.
     
     - Parameter eventDetails: <Dictionary<String, AnyObject> A single Event item to be persisted to the Datastore.
     - Returns: Void
     */
    func saveEvent(_ eventTitle: String?) {
        
        //Minion Context worker with Private Concurrency type.
        let minionManagedObjectContextWorker: NSManagedObjectContext =
            NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
        minionManagedObjectContextWorker.parent = self.mainContextInstance
        
        //Create new Object of Event entity
        let eventItem = NSEntityDescription.insertNewObject(forEntityName: EntityTypes.Event.rawValue,
                                                            into: minionManagedObjectContextWorker) as! Event
        if eventTitle == nil {
            eventItem.title = "mocked event title"
        } else {
            eventItem.title = eventTitle!
            eventItem.city = "The Hague"
            eventItem.country = "The Netherlands"
            eventItem.fb_url =  URL(string: "http://example.com") as AnyObject
            eventItem.ticket_url = URL(string: "http://example.com") as AnyObject
            eventItem.date = Date()
            eventItem.eventId = "1234"
        }
        
        //Save current work on Minion workers
        self.persistenceManager.saveWorkerContext(minionManagedObjectContextWorker)
        
        //Save and merge changes from Minion workers with Main context
        self.persistenceManager.mergeWithMainContext()
        
        //Post notification to update datasource of a given Viewcontroller/UITableView
        self.postUpdateNotification()
    }

    /**
        Create new Events from a given list, and persist it to Datastore via Worker(minion),
        that synchronizes with Main context.
    
        - Parameter eventsList: Array<AnyObject> Contains events to be persisted to the Datastore.
        - Returns: Void
    */
    func saveEventsList(_ eventsList: Array<AnyObject>) {
        DispatchQueue.global().async {

            //Minion Context worker with Private Concurrency type.
            let minionManagedObjectContextWorker: NSManagedObjectContext =
                NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
            minionManagedObjectContextWorker.parent = self.mainContextInstance

            //Create eventEntity, process member field values
{'fraction_non_alphanumeric': 0.059859821935972723, 'fraction_numerical': 0.0013260087137715476, 'mean_word_length': 2.728460451977401, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '329624', 'n_tokens_mistral': 2573, 'n_tokens_neox': 2479, 'n_words': 752}