<commit_before>//
//  SetupViewModel.swift
//  HomeControl
//
//  Created by <NAME> on 22/11/15.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import ReactiveCocoa
import Alamofire

enum SetupError: ErrorType {
    case EncodingError
    case DownloadError(NSError)
}

class SetupViewModel {

    //MARK: Properties

    let serverAddress = MutableProperty("")
    let username = MutableProperty("")
    let password = MutableProperty("")
    let loadButtonEnabled = MutableProperty(false)

    var downloadAction: Action<Void, Void, SetupError>!

    //MARK: Initialization

    init() {
        loadButtonEnabled <~ combineLatest(serverAddress.producer, username.producer, password.producer).map { (serverAddressText, usernameText, passwordText) in
            if serverAddressText.isEmpty || usernameText.isEmpty || passwordText.isEmpty { return false }
            return true
        }

        downloadAction = Action(enabledIf: loadButtonEnabled) { [unowned self] in
            self.downloadStructureFile()
        }
    }

    //MARK: Download Structure File

    private func downloadStructureFile() -> SignalProducer<Void, SetupError> {
        guard let encodedServerAddress = serverAddress.value.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()),
                  credentialData = "\(username.value):\(password.value)".dataUsingEncoding(NSUTF8StringEncoding) else {
                return SignalProducer(error: .EncodingError)
        }

        let destination = Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
        let url = "http://\(encodedServerAddress)/data/LoxAPP2.xml"
        let base64Credentials = credentialData.base64EncodedStringWithOptions([])
        let headers = ["Authorization": "Basic \(base64Credentials)"]

        return SignalProducer { observer, _ in
            download(.GET, url, headers: headers, destination: destination).response { _, _, _, error in
                if let error = error {
                    observer.sendFailed(.DownloadError(error))
                }

                observer.sendCompleted()
            }
        }
    }
}<commit_msg>Remove old structure file before downloading<commit_after>//
//  SetupViewModel.swift
//  HomeControl
//
//  Created by <NAME> on 22/11/15.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import ReactiveCocoa
import Alamofire

enum SetupError: ErrorType {
    case EncodingError
    case DownloadError(NSError)
    case FileError(ErrorType?)
}

class SetupViewModel {

    //MARK: Properties

    let serverAddress = MutableProperty("")
    let username = MutableProperty("")
    let password = MutableProperty("")
    let loadButtonEnabled = MutableProperty(false)

    var downloadAction: Action<Void, Void, SetupError>!

    //MARK: Initialization

    init() {
        loadButtonEnabled <~ combineLatest(serverAddress.producer, username.producer, password.producer).map { (serverAddressText, usernameText, passwordText) in
            if serverAddressText.isEmpty || usernameText.isEmpty || passwordText.isEmpty { return false }
            return true
        }

        downloadAction = Action(enabledIf: loadButtonEnabled) { [unowned self] in
            self.downloadStructureFile()
        }
    }

    //MARK: Download Structure File

    private func downloadStructureFile() -> SignalProducer<Void, SetupError> {
        guard let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first,
            structureFilePath = NSURL.fileURLWithPath(documentDirectory).URLByAppendingPathComponent("LoxAPP2.xml").path else {
                return SignalProducer(error: .FileError(nil))
        }

        let fileManager = NSFileManager.defaultManager()

        if fileManager.fileExistsAtPath(structureFilePath) {
            do {
                try fileManager.removeItemAtPath(structureFilePath)
            } catch {
                return SignalProducer(error: .FileError(error))
            }
        }

        guard let encodedServerAddress = serverAddress.value.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()),
                  credentialData = "\(username.value):\(password.value)".dataUsingEncoding(NSUTF8StringEncoding) else {
                return SignalProducer(error: .EncodingError)
        }

        let destination = Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
        let url = "http://\(encodedServerAddress)/data/LoxAPP2.xml"
        let base64Credentials = credentialData.base64EncodedStringWithOptions([])
        let headers = ["Authorization": "Basic \(base64Credentials)"]

        return SignalProducer { observer, _ in
            download(.GET, url, headers: headers, destination: destination).response { _, _, _, error in
                if let error = error {
                    observer.sendFailed(.DownloadError(error))
                }

                observer.sendCompleted()
            }
        }
    }
}
{'fraction_non_alphanumeric': 0.09468503937007874, 'fraction_numerical': 0.007283464566929134, 'mean_word_length': 2.8203007518796994, 'pattern_counts': {'":': 2, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 3}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 19, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1443786', 'n_tokens_mistral': 1352, 'n_tokens_neox': 1268, 'n_words': 285}