<commit_before>//
//  AccountManager.swift
//  JenkinsiOS
//
//  Created by Robert on 25.09.16.
//  Copyright © 2016 MobiLab Solutions. All rights reserved.
//

import Foundation
import SAMKeychain

class AccountManager{
    
    static let manager = AccountManager()
    
    /// The list of all accounts
    var accounts: [Account] = []
    
    private init(){
        accounts = getAccounts()
    }
    
    /// Add an account to the list of available accounts
    ///
    /// - parameter account: The account to add
    func addAccount(account: Account){
        
        accounts.append(account)
        
        if let username = account.username, let password = account.password{
            SAMKeychain.setPassword(password, forService: "com.mobilabsolutions.jenkins.account", account: username)
        }
        
        var url = getDocumentDirectory()?.appendingPathComponent("Account")
        
        if !FileManager.default.fileExists(atPath: url!.absoluteString){
            _ = try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
        }
        
        url?.appendPathComponent(account.baseUrl.absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)!)
        
        print(NSKeyedArchiver.archiveRootObject(account, toFile: url!.path))
    }
    
    /// Return the full list of accounts
    ///
    /// - returns: The list of user added accounts
    func getAccounts() -> [Account]{
        
        var accounts: [Account] = []
        
        // The accounts that are available in our Keychain service. Relevant data here: account, password
        let keychainAccounts = SAMKeychain.accounts(forService: "com.mobilabsolutions.jenkins.account").flatMap { (arr) -> [String: String] in
            // Only the username and password are relevant here, therefore, we flat map
            // the array to a dictionary that maps usernames to passwords
            var returnDict: [String: String]  = [:]
            for entry in arr{
                returnDict[entry["acct"] as! String] = entry["password"] as? String
            }
            return returnDict
        }
        
        let url = getDocumentDirectory()?.appendingPathComponent("Account")
        
        do{
            let urls = try FileManager.default.contentsOfDirectory(at: url!, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
            for fileUrl in urls{
                if let account = NSKeyedUnarchiver.unarchiveObject(withFile: fileUrl.path) as? Account{
                    
                    if let username = account.username{
                        account.password = keychainAccounts?[username]
                    }
                    
                    accounts.append(account)
                }
            }
        }
        catch{
            print(error)
        }
        return accounts
    }


    /// Get the url for the document directory with a path component added
    ///
    /// - parameter path:      The path component that should be added to the directory
    /// - parameter directory: Whether or not the path is a directory
    ///
    /// - returns: The URL describing the document directory with the added path component
    private func getDocumentDirectory() -> URL?{
        return (try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true))
    }
    
}<commit_msg>Update to use PersistenceUtitlites class<commit_after>//
//  AccountManager.swift
//  JenkinsiOS
//
//  Created by Robert on 25.09.16.
//  Copyright © 2016 MobiLab Solutions. All rights reserved.
//

import Foundation
import SAMKeychain

class AccountManager{
    
    static let manager = AccountManager()
    
    /// The list of all accounts
    var accounts: [Account] = []
    
    private init(){
        accounts = getAccounts()
    }
    
    /// Add an account to the list of available accounts
    ///
    /// - parameter account: The account to add
    func addAccount(account: Account){
        
        accounts.append(account)
        
        if let username = account.username, let password = account.password{
            SAMKeychain.setPassword(password, forService: "com.mobilabsolutions.jenkins.account", account: username)
        }
        
        var url = PersistenceUtils.getDocumentDirectory()?.appendingPathComponent("Account")
        
        if !FileManager.default.fileExists(atPath: url!.absoluteString){
            _ = try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
        }
        
        url?.appendPathComponent(account.baseUrl.absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)!)
        
        NSKeyedArchiver.archiveRootObject(account, toFile: url!.path)
    }
    
    /// Return the full list of accounts
    ///
    /// - returns: The list of user added accounts
    func getAccounts() -> [Account]{
        
        var accounts: [Account] = []
        
        // The accounts that are available in our Keychain service. Relevant data here: account, password
        let keychainAccounts = SAMKeychain.accounts(forService: "com.mobilabsolutions.jenkins.account").flatMap { (arr) -> [String: String] in
            // Only the username and password are relevant here, therefore, we flat map
            // the array to a dictionary that maps usernames to passwords
            var returnDict: [String: String]  = [:]
            for entry in arr{
                returnDict[entry["acct"] as! String] = entry["password"] as? String
            }
            return returnDict
        }
        
        let url = PersistenceUtils.getDocumentDirectory()?.appendingPathComponent("Account")
        
        do{
            let urls = try FileManager.default.contentsOfDirectory(at: url!, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
            for fileUrl in urls{
                if let account = NSKeyedUnarchiver.unarchiveObject(withFile: fileUrl.path) as? Account{
                    
                    if let username = account.username{
                        account.password = keychainAccounts?[username]
                    }
                    
                    accounts.append(account)
                }
            }
        }
        catch{
            print(error)
        }
        return accounts
    }    
}
{'fraction_non_alphanumeric': 0.08916111024965111, 'fraction_numerical': 0.0031012560086835167, 'mean_word_length': 2.0083955223880596, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '497158', 'n_tokens_mistral': 1656, 'n_tokens_neox': 1604, 'n_words': 466}