<commit_before>//
//  Documente+AppKitFacilities.swift
//  BartlebyKit
//
//  Created by <NAME> on 08/07/2016.
//
//

import Foundation

#if os(OSX)
    import AppKit
#else
    import UIKit
#endif

#if !USE_EMBEDDED_MODULES
    import Alamofire
#endif


extension BartlebyDocument {

    #if os(OSX)

    //MARK: - APP KIT FACILITIES


    public func saveMetadata(handlers: Handlers){
        let savePanel = NSSavePanel()
        savePanel.canCreateDirectories = true
        savePanel.nameFieldStringValue = self.fileURL?.lastPathComponent ?? "metadata"
        savePanel.allowedFileTypes=["bart"]
        savePanel.begin(completionHandler: { (result) in
            Bartleby.syncOnMain{
                if result.hashValue==NSFileHandlingPanelOKButton{
                    if let url = savePanel.url {
                        let filePath=url.path
                        self.exportMetadataTo(filePath, handlers:handlers)
                    }
                }
            }
        })
    }


    public func loadMetadata(handlers: Handlers){
        let openPanel = NSOpenPanel()
        openPanel.canCreateDirectories = false
        openPanel.allowedFileTypes=["bart"]
        openPanel.begin(completionHandler: { (result) in
            Bartleby.syncOnMain{
                if result.hashValue==NSFileHandlingPanelOKButton{
                    if let url = openPanel.url {
                        let filePath=url.path
                        self.importMetadataFrom(filePath,handlers:handlers)

                    }
                }
            }
        })
    }


    #endif

    /**
     Call the export Endpoint

     - parameter handlers: the handlers
     */
    public func importCollectionsFromCollaborativeServer(_ handlers: Handlers){
        self.currentUser.login( sucessHandler: {

            let pathURL=self.baseURL.appendingPathComponent("/Export")
            let dictionary=["excludeTriggers":"true","observationUID":self.metadata.persistentUID];

            let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:self.UID, withActionName:"Export", forMethod:"GET", and: pathURL)

            do {
                let r=try URLEncoding().encode(urlRequest,with:dictionary)
                request(r).validate().responseJSON(completionHandler: { (response) in

                    let result=response.result
                    let httpResponse=response.response

                    if result.isFailure {
                        let completionState = Completion.failureStateFromAlamofire(response)
                        handlers.on(completionState)
                    } else {

                        if let statusCode=httpResponse?.statusCode {
                            if 200...299 ~= statusCode {
                                var issues=[String]()

                                // #TODO We should use the collections name
                                // And directly deserialize with the dynamic deserializer

                                /*
                                if let dictionary=result.value as? [String:Any]{
                                    if let collections=dictionary["collections"] as? [String:Any] {
                                        for (collectionName,collectionData) in collections{
                                            if let proxy=self.collectionByName(collectionName),
                                                let collectionDictionary=collectionData as? [Any]{
                                                for itemRep in collectionDictionary{
                                                    if let itemRepDictionary = itemRep as? [String:Any]{
                                                        do {
                                                            if let instance=try self.serializer.deserializeFromDictionary(itemRepDictionary, register: false) as? Collectible{
                                                                if let user:User=instance as? User{
                                                                    // We donnot want to expose the document current user
                                                                    if user.creatorUID != user.UID{
                                                                        proxy.upsert(instance,commit:false)
                                                                    }
                                                                }else{
                                                                    // We want to upsert any object
                                                                    proxy.upsert(instance,commit:false)
                                                                }
                                                            }
                                                        }catch{
                                                            issues.append("\(error)")
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                 */
                                if issues.count==0{
                                    handlers.on(Completion.successState())
                                }else{
                                    handlers.on(Completion.failureState(issues.joined(separator: "\n"), statusCode: StatusOfCompletion.expectation_Failed))
                                }
                            } else {
                                var status = StatusOfCompletion.undefined
                                if let statusCode=httpResponse?.statusCode{
                                    status = StatusOfCompletion (rawValue:statusCode) ?? StatusOfCompletion.undefined
                                }
                                handlers.on(Completion.failureState("\(result)", statusCode:status ))
                            }
                        }
                    }
                })
            }catch{
                handlers.on(Completion.failureStateFromError(error))
            }

        }) { (context) in
            handlers.on(Completion.failureStateFromHTTPContext(context))<commit_msg>Dot Bart support for Swift 4<commit_after>//
//  Documente+AppKitFacilities.swift
//  BartlebyKit
//
//  Created by <NAME> on 08/07/2016.
//
//

import Foundation

#if os(OSX)
    import AppKit
#else
    import UIKit
#endif

#if !USE_EMBEDDED_MODULES
    import Alamofire
#endif


extension BartlebyDocument {

    #if os(OSX)

    //MARK: - APP KIT FACILITIES


    public func saveMetadata(handlers: Handlers){
        let savePanel = NSSavePanel()
        savePanel.canCreateDirectories = true
        savePanel.nameFieldStringValue = self.fileURL?.lastPathComponent ?? "metadata"
        savePanel.allowedFileTypes=["bart"]
        savePanel.begin(completionHandler: { (result) in
            Bartleby.syncOnMain{
                if result.hashValue==NSFileHandlingPanelOKButton{
                    if let url = savePanel.url {
                        let filePath=url.path
                        self.exportMetadataTo(filePath, handlers:handlers)
                    }
                }
            }
        })
    }


    public func loadMetadata(handlers: Handlers){
        let openPanel = NSOpenPanel()
        openPanel.canCreateDirectories = false
        openPanel.allowedFileTypes=["bart"]
        openPanel.begin(completionHandler: { (result) in
            Bartleby.syncOnMain{
                if result.hashValue==NSFileHandlingPanelOKButton{
                    if let url = openPanel.url {
                        let filePath=url.path
                        self.importMetadataFrom(filePath,handlers:handlers)

                    }
                }
            }
        })
    }


    #endif

    /**
     Call the export Endpoint

     - parameter handlers: the handlers
     */
    public func importCollectionsFromCollaborativeServer(_ handlers: Handlers){
        self.currentUser.login( sucessHandler: {

            let pathURL=self.baseURL.appendingPathComponent("/Export")
            let dictionary=["excludeTriggers":"true","observationUID":self.metadata.persistentUID];

            let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:self.UID, withActionName:"Export", forMethod:"GET", and: pathURL)

            do {
                let r=try URLEncoding().encode(urlRequest,with:dictionary)
                request(r).validate().responseJSON(completionHandler: { (response) in

                    let result=response.result
                    let httpResponse=response.response

                    if result.isFailure {
                        let completionState = Completion.failureStateFromAlamofire(response)
                        handlers.on(completionState)
                    } else {

                        if let statusCode=httpResponse?.statusCode {
                            if 200...299 ~= statusCode {
                                var issues=[String]()
                                if let dictionary=result.value as? [String:Any]{
                                    if let collections=dictionary["collections"] as? [String:Any] {
                                        for (collectionName,collectionDictionary) in collections{
                                            if let proxy=self.collectionByName(collectionName),
                                                let collectionDictionary=collectionDictionary as? [String:Any] {
                                                do{
                                                    let jsonData = try JSONSerialization.data(withJSONObject: collectionDictionary, options:[])
                                                    // Use the dynamics
                                                    let collection=try self.dynamics.deserialize(typeName: collectionName, data: jsonData, document: nil)
                                                    // We need to cast the dynamic type to ManagedModel & BartlebyCollection (BartlebyCollection alone is not enough)
                                                    if let bartlebyCollection = collection as? ManagedModel & BartlebyCollection{
                                                        proxy.append(bartlebyCollection.getItems(), commit: false, isUndoable: false)
                                                    }else{
                                                        throw DocumentError.collectionProxyTypeError
                                                    }

                                                }catch{
                                                    issues.append("\(error)")
                                                }
                                            }
                                        }
                                    }
                                }
                                if issues.count==0{
                                    handlers.on(Completion.successState())
                                }else{
                                    handlers.on(Completion.failureState(issues.joined(separator: "\n"), statusCode: StatusOfCompletion.expectation_Failed))
                                }
                            } else {
                                var status = StatusOfCompletion.undefined
                                if let statusCode=httpResponse?.statusCode{
                                    status = StatusOfCompletion (rawValue:statusCode) ?? StatusOfCompletion.undefined
                                }
                                handlers.on(Completion.failureState("\(result)", statusCode:status ))
                            }
                        }
                    }

                })
            }catch{
                handlers.on(Completion.failureStateFromError(error))
            }

        }) { (context) in
            handlers.on(Completion.failureStateFromHTTPContext(context))
{'fraction_non_alphanumeric': 0.0687739933022952, 'fraction_numerical': 0.0025320591358327206, 'mean_word_length': 1.030514096185738, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 109, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '254631', 'n_tokens_mistral': 2537, 'n_tokens_neox': 2367, 'n_words': 475}