<commit_before>//
//  SetupCollaborativeServerViewController.swift
//  BartlebysUI
//
//  Created by <NAME> on 29/12/2016.
//  Copyright © 2016 Chaosmos SAS. All rights reserved.
//

import Cocoa
import BartlebyKit

class SetupCollaborativeServerViewController: IdentityStepViewController{

    // During dev you can setup to false (not to consume SMS credits)
    let relayActivationCode:Bool=false

    override var nibName : String { return "SetupCollaborativeServerViewController" }

    @IBOutlet weak var box: NSBox!

    @IBOutlet weak var explanationsTextField: NSTextField!

    @IBOutlet weak var serverComboBox: NSComboBox!

    @IBOutlet weak var messageTextField: NSTextField!

    override func viewWillAppear() {
        super.viewWillAppear()
        self.explanationsTextField.stringValue=NSLocalizedString("Select or register a Collaborative Server  API URL.", comment: "Select the Collaborative Server API URL")
        if let document=self.documentProvider?.getDocument(){
            var servers=Bartleby.configuration.defaultBaseURLList
            servers.append(NSLocalizedString("Add a Server", comment: "Add a Server"))
            self.serverComboBox.addItems(withObjectValues:servers)
            self.serverComboBox.selectItem(at: 0)
        }
    }

    override func proceedToValidation(){
        super.proceedToValidation()
        if let document=self.documentProvider?.getDocument(),
            let identityWindowController=self.identityWindowController{
            if let serverURL:URL=URL(string:self.serverComboBox.stringValue){
                self.stepDelegate?.disableActions()
                Async.main{
                    HTTPManager.apiIsReachable(serverURL, successHandler: {
                        // We prefer to wait for reachability response before to disable the actions

                        // The server is Reachable
                        self.messageTextField.stringValue=""

                        // Should we create a USER?
                        var matchingProfile:Profile?
                        var userHasBeenFound=false
                        if let identification=identityWindowController.identification{
                            // Check if we should reuse a password or an external ID.
                            matchingProfile=IdentitiesManager.profileMatching(identification: identification, inDocument: document)
                            if let matchingProfile=matchingProfile{
                                if document.spaceUID == matchingProfile.documentSpaceUID &&
                                    PString.trim(document.baseURL.absoluteString) == PString.trim(matchingProfile.url.absoluteString){
                                    if let user = matchingProfile.user {
                                        // We should reuse the user.
                                        document.users.add(user, commit: false)
                                        document.metadata.memorizeUser(user)
                                        userHasBeenFound=true
                                    }
                                }
                            }
                        }

                        if userHasBeenFound==false{
                            // In rare situation we prefer to push manually the entities
                            // To do so we do not commit the object created by the newObject() factory
                            var user:User=document.newObject(commit:false)
                            user.email=identityWindowController.identification?.email
                            user.phoneCountryCode=identityWindowController.identification?.phoneCountryCode
                            user.phoneNumber=identityWindowController.identification?.phoneNumber
                            user.externalID=identityWindowController.identification?.externalID
                            user.supportsPasswordSyndication=identityWindowController.identification?.supportsPasswordSyndication ?? false
                            if let matchingProfile=matchingProfile {
                                if let matchingUser=matchingProfile.user{
                                    if user.supportsPasswordSyndication == true{
                                        user.password=<PASSWORD>
                                        user.externalID=matchingUser.externalID
                                    }

                                }
                            }
                            document.metadata.memorizeUser(user)
                        }

                        func __postCreationPhase(user:User){
                            // The user has been successfully pushed
                            // Let's login
                            user.login(sucessHandler: {
                                let locker:Locker=document.newObject(commit:false)
                                locker.startDate=Date()// now
                                locker.endDate=Date.distantFuture//
                                locker.doNotCommit {
                                    locker.gems=document.metadata.sugar
                                    locker.associatedDocumentUID=document.UID
                                    locker.subjectUID=document.UID
                                    locker.userUID=user.UID
                                    locker.mode = .persistent
                                    // Store the locker UID
                                    document.metadata.lockerUID=locker.UID<commit_msg>Do not inject undefined user externalID on new document preparation<commit_after>//
//  SetupCollaborativeServerViewController.swift
//  BartlebysUI
//
//  Created by <NAME> on 29/12/2016.
//  Copyright © 2016 Chaosmos SAS. All rights reserved.
//

import Cocoa
import BartlebyKit

class SetupCollaborativeServerViewController: IdentityStepViewController{

    // During dev you can setup to false (not to consume SMS credits)
    let relayActivationCode:Bool=false

    override var nibName : String { return "SetupCollaborativeServerViewController" }

    @IBOutlet weak var box: NSBox!

    @IBOutlet weak var explanationsTextField: NSTextField!

    @IBOutlet weak var serverComboBox: NSComboBox!

    @IBOutlet weak var messageTextField: NSTextField!

    override func viewWillAppear() {
        super.viewWillAppear()
        self.explanationsTextField.stringValue=NSLocalizedString("Select or register a Collaborative Server  API URL.", comment: "Select the Collaborative Server API URL")
        if let document=self.documentProvider?.getDocument(){
            var servers=Bartleby.configuration.defaultBaseURLList
            servers.append(NSLocalizedString("Add a Server", comment: "Add a Server"))
            self.serverComboBox.addItems(withObjectValues:servers)
            self.serverComboBox.selectItem(at: 0)
        }
    }

    override func proceedToValidation(){
        super.proceedToValidation()
        if let document=self.documentProvider?.getDocument(),
            let identityWindowController=self.identityWindowController{
            if let serverURL:URL=URL(string:self.serverComboBox.stringValue){
                self.stepDelegate?.disableActions()
                Async.main{
                    HTTPManager.apiIsReachable(serverURL, successHandler: {
                        // We prefer to wait for reachability response before to disable the actions

                        // The server is Reachable
                        self.messageTextField.stringValue=""

                        // Should we create a USER?
                        var matchingProfile:Profile?
                        var userHasBeenFound=false
                        if let identification=identityWindowController.identification{
                            // Check if we should reuse a password or an external ID.
                            matchingProfile=IdentitiesManager.profileMatching(identification: identification, inDocument: document)
                            if let matchingProfile=matchingProfile{
                                if document.spaceUID == matchingProfile.documentSpaceUID &&
                                    PString.trim(document.baseURL.absoluteString) == PString.trim(matchingProfile.url.absoluteString){
                                    if let user = matchingProfile.user {
                                        // We should reuse the user.
                                        document.users.add(user, commit: false)
                                        document.metadata.memorizeUser(user)
                                        userHasBeenFound=true
                                    }
                                }
                            }
                        }

                        if userHasBeenFound==false{
                            // In rare situation we prefer to push manually the entities
                            // To do so we do not commit the object created by the newObject() factory
                            var user:User=document.newObject(commit:false)
                            user.email=identityWindowController.identification?.email
                            user.phoneCountryCode=identityWindowController.identification?.phoneCountryCode
                            user.phoneNumber=identityWindowController.identification?.phoneNumber
                            if let externalID=identityWindowController.identification?.externalID{
                                if externalID != Default.NO_UID{
                                    user.externalID=externalID
                                }
                            }
                            user.supportsPasswordSyndication=identityWindowController.identification?.supportsPasswordSyndication ?? false
                            if let matchingProfile=matchingProfile {
                                if let matchingUser=matchingProfile.user{
                                    if user.supportsPasswordSyndication == true{
                                        user.password=<PASSWORD>
                                        user.externalID=matchingUser.externalID
                                    }

                                }
                            }
                            document.metadata.memorizeUser(user)
                        }

                        func __postCreationPhase(user:User){
                            // The user has been successfully pushed
                            // Let's login
                            user.login(sucessHandler: {
                                let locker:Locker=document.newObject(commit:false)
                                locker.startDate=Date()// now
                                locker.endDate=Date.distantFuture//
                                locker.doNotCommit {
                                    locker.gems=document.metadata.sugar
                                    locker.associatedDocumentUID=document.UID
                                    locker.subjectUID=document.UID
                                    locker.userUID=user.UID
                                    locker.mode = .persistent
                                    // Store the locker UID
                                    document.metadata.lockerUID=locker.UID
{'fraction_non_alphanumeric': 0.05824050521884045, 'fraction_numerical': 0.002280501710376283, 'mean_word_length': 1.3480230642504119, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 53, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5527958', 'n_tokens_mistral': 2428, 'n_tokens_neox': 2266, 'n_words': 520}