<commit_before>//
//  waterwheel.swift
//
//  Created by <NAME> on 1/25/16.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Alamofire
import SwiftyJSON

public enum EntityType: String {
    case Node = "node", Comment = "comment"
}

// MARK: - Typelias definitions

public typealias completion = (success:Bool, response:Response<AnyObject, NSError>?, json:SwiftyJSON.JSON?, error:NSError!) -> Void
public typealias stringcompletion = (success:Bool, response:Response<String, NSError>?, json:SwiftyJSON.JSON?, error:NSError!) -> Void
public typealias paramType = [String: AnyObject]?


private let waterwheelErrorString = "waterhwheel error: "

/**
 Responsible for storing state and variables for waterwheel.
 */
public class waterwheelManager {


    // MARK: - Properties

    /**
     A shared instance of `waterwheelManager`
     */
    public static let sharedInstance: waterwheelManager = {
        return waterwheelManager()
    }()

    public let requestFormat = "?_format=json"
    var headers = [
        "Content-Type":"application/json",
        "Accept":"application/json",
        ]
    public var URL : String = ""
    public var basicUsername : String = ""
    public var basicPassword : String = ""
    public var CSRFToken : String = ""
    public var signRequestsBasic : Bool = false
    public var signCSRFToken : Bool = false
    private var isLoggedIn: Bool = false
}


/**
 Sets the URL for all requests to be sent against.
 
 - parameter drupalURL:         The URL for the Drupal Site
 
 */
public func setDrupalURL(drupalURL: String) {
    assert(drupalURL != "", waterwheelErrorString + "Missing Drupal URL")
    waterwheelManager.sharedInstance.URL = drupalURL;
    waterwheel.checkLoginStatus()
}

/** 
 Private function to set Logged in Status
*/
private func setIsLoggedIn(isLoggedIn: Bool) {
    waterwheelManager.sharedInstance.isLoggedIn = isLoggedIn
}

/**
 Public function to check if the user is logged in

 */
public func isLoggedIn() -> Bool {
    return waterwheelManager.sharedInstance.isLoggedIn
}


/**
 Private function to check Login Status with all cookies that have been set.

 */
private func checkLoginStatus() {
    let urlString = waterwheelManager.sharedInstance.URL + "/user/login_status" + waterwheelManager.sharedInstance.requestFormat
    Alamofire.request(.GET, urlString)
        .validate(statusCode: 200..<300)
        .responseString{ response in
            if (response.result.error == nil) {
                let loginStatus = String(data: response.data!, encoding: NSUTF8StringEncoding)
                if (loginStatus == "1") {
                    waterwheelManager.sharedInstance.isLoggedIn = true
                } else {
                    waterwheelManager.sharedInstance.isLoggedIn = false
                }

            }
            else {
                waterwheelManager.sharedInstance.isLoggedIn = false
            }
    }
}


// MARK: - Authentication methodss

/**
 Allows a username and password to be set for Basic Auth

 - parameter username:          The username to login with.
 - parameter password:          The password to login with

 */
public func setBasicAuthUsernameAndPassword(username:String, password:String) {
    waterwheelManager.sharedInstance.basicUsername = username
    waterwheelManager.sharedInstance.basicPassword = password
    waterwheelManager.sharedInstance.signRequestsBasic = true
    setIsLoggedIn(true)
}


/**
 Login

 - parameter username:          The username to login with.
 - parameter password:          The password to login with
 - parameter completionHandler: A completion handler that your delegate method should call if you want the response.


 */
public func login(username:String?, password:String?, completionHandler: stringcompletion?) {
    let urlString = waterwheelManager.sharedInstance.URL + "/user/login" + waterwheelManager.sharedInstance.requestFormat

    assert(username! != "", waterwheelErrorString + "Missing username.")
    assert(password! != "", waterwheelErrorString + "Missing password.")

    let body = [
        "name":username!,
        "pass":password!
    ]

    // POST request to login.
    Alamofire.request(.POST, urlString, headers: waterwheelManager.sharedInstance.headers, parameters: body, encoding: .JSON)
        .validate(statusCode: 200..<300)
        .responseString { response in
            if (response.result.error == nil) {
                waterwheel.setIsLoggedIn(true)
                //We have to get our CSRF token in order to ensure we can make POST, PUT, and DELETE requests.
                getCSRFToken({ (success, response, json, error) in
                    if (success) {
                        completionHandler?(success: true, response: response, json: nil, error: nil)
                    } else {
                        //Failed to get CSRF token for some reason
                        completionHandler?(success: false, response: response, json: nil, error: nil)
                    }
                })
            }
            else {
                waterwheel.setIsLoggedIn(false)
                completionHandler?(success: false, response: response, json: nil, error: response.result.error)
            }
    }
}



/**
 Logout a user

 - parameter completionHandler: A completion handler that your delegate method should call if you want the response.

 */

public func logout(completionHandler: stringcompletion?) {
    if waterwheelManager.sharedInstance.signRequestsBasic  {
        waterwheelManager.sharedInstance.basicUsername = ""
        waterwheelManager.sharedInstance.basicPassword = ""
        waterwheelManager.sharedInstance.signRequestsBasic = false
        return
    }
    let urlString = waterwheelManager.sharedInstance.URL + "/user/logout"
    Alamofire.request(.GET, urlString)
        .validate(statusCode: 200..<300)
        .responseString { response in
            if (response.result.error == nil) {
                waterwheelManager.sharedInstance.CSRFToken = ""
                waterwheelManager.sharedInstance.signCSRFToken = false
                completionHandler?(success: true, response: response, json: nil, error: response.result.error)
            }
            else {
                completionHandler?(success: false, response: response, json: nil, error: response.result.error)
            }
    }

}

/**
 
 Private function to get the CSRF Token
 <commit_msg>Fixes an issue that waterwheel to believe you are logged in<commit_after>//
//  waterwheel.swift
//
//  Created by <NAME> on 1/25/16.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Alamofire
import SwiftyJSON

public enum EntityType: String {
    case Node = "node", Comment = "comment"
}

// MARK: - Typelias definitions

public typealias completion = (success:Bool, response:Response<AnyObject, NSError>?, json:SwiftyJSON.JSON?, error:NSError!) -> Void
public typealias stringcompletion = (success:Bool, response:Response<String, NSError>?, json:SwiftyJSON.JSON?, error:NSError!) -> Void
public typealias paramType = [String: AnyObject]?


private let waterwheelErrorString = "waterhwheel error: "

/**
 Responsible for storing state and variables for waterwheel.
 */
public class waterwheelManager {


    // MARK: - Properties

    /**
     A shared instance of `waterwheelManager`
     */
    public static let sharedInstance: waterwheelManager = {
        return waterwheelManager()
    }()

    public let requestFormat = "?_format=json"
    var headers = [
        "Content-Type":"application/json",
        "Accept":"application/json",
        ]
    public var URL : String = ""
    public var basicUsername : String = ""
    public var basicPassword : String = ""
    public var CSRFToken : String = ""
    public var signRequestsBasic : Bool = false
    public var signCSRFToken : Bool = false
    private var isLoggedIn: Bool = false
}


/**
 Sets the URL for all requests to be sent against.
 
 - parameter drupalURL:         The URL for the Drupal Site
 
 */
public func setDrupalURL(drupalURL: String) {
    assert(drupalURL != "", waterwheelErrorString + "Missing Drupal URL")
    waterwheelManager.sharedInstance.URL = drupalURL;
    waterwheel.checkLoginStatus()
}

/** 
 Private function to set Logged in Status
*/
private func setIsLoggedIn(isLoggedIn: Bool) {
    waterwheelManager.sharedInstance.isLoggedIn = isLoggedIn
}

/**
 Public function to check if the user is logged in

 */
public func isLoggedIn() -> Bool {
    return waterwheelManager.sharedInstance.isLoggedIn
}


/**
 Private function to check Login Status with all cookies that have been set.

 */
private func checkLoginStatus() {
    print("Checking login status")
    let urlString = waterwheelManager.sharedInstance.URL + "/user/login_status" + waterwheelManager.sharedInstance.requestFormat
    Alamofire.request(.GET, urlString)
        .validate(statusCode: 200..<300)
        .responseString{ response in
            if (response.result.error == nil) {
                let loginStatus = String(data: response.data!, encoding: NSUTF8StringEncoding)
                if (loginStatus == "1") {
                    waterwheelManager.sharedInstance.isLoggedIn = true
                } else {
                    waterwheelManager.sharedInstance.isLoggedIn = false
                }

            }
            else {
                waterwheelManager.sharedInstance.isLoggedIn = false
            }
    }
}


// MARK: - Authentication methodss

/**
 Allows a username and password to be set for Basic Auth

 - parameter username:          The username to login with.
 - parameter password:          The password to login with

 */
public func setBasicAuthUsernameAndPassword(username:String, password:String) {
    waterwheelManager.sharedInstance.basicUsername = username
    waterwheelManager.sharedInstance.basicPassword = password
    waterwheelManager.sharedInstance.signRequestsBasic = true
    setIsLoggedIn(true)
}


/**
 Login

 - parameter username:          The username to login with.
 - parameter password:          The password to login with
 - parameter completionHandler: A completion handler that your delegate method should call if you want the response.


 */
public func login(username:String?, password:String?, completionHandler: stringcompletion?) {
    let urlString = waterwheelManager.sharedInstance.URL + "/user/login" + waterwheelManager.sharedInstance.requestFormat

    assert(username! != "", waterwheelErrorString + "Missing username.")
    assert(password! != "", waterwheelErrorString + "Missing password.")

    let body = [
        "name":username!,
        "pass":password!
    ]

    // POST request to login.
    Alamofire.request(.POST, urlString, headers: waterwheelManager.sharedInstance.headers, parameters: body, encoding: .JSON)
        .validate(statusCode: 200..<300)
        .responseString { response in
            if (response.result.error == nil) {
                waterwheel.setIsLoggedIn(true)
                //We have to get our CSRF token in order to ensure we can make POST, PUT, and DELETE requests.
                getCSRFToken({ (success, response, json, error) in
                    if (success) {
                        completionHandler?(success: true, response: response, json: nil, error: nil)
                    } else {
                        //Failed to get CSRF token for some reason
                        completionHandler?(success: false, response: response, json: nil, error: nil)
                    }
                })
            }
            else {
                waterwheel.setIsLoggedIn(false)
                completionHandler?(success: false, response: response, json: nil, error: response.result.error)
            }
    }
}



/**
 Logout a user

 - parameter completionHandler: A completion handler that your delegate method should call if you want the response.

 */

public func logout(completionHandler completionHandler: stringcompletion?) {
    if waterwheelManager.sharedInstance.signRequestsBasic  {
        waterwheelManager.sharedInstance.basicUsername = ""
        waterwheelManager.sharedInstance.basicPassword = ""
        waterwheelManager.sharedInstance.signRequestsBasic = false
        return
    }
    let urlString = waterwheelManager.sharedInstance.URL + "/user/logout"
    Alamofire.request(.GET, urlString)
        .validate(statusCode: 200..<300)
        .responseString { response in
            if (response.result.error == nil) {
                waterwheelManager.sharedInstance.CSRFToken = ""
                waterwheelManager.sharedInstance.signCSRFToken = false
                waterwheelManager.sharedInstance.isLoggedIn = false
                completionHandler?(success: true, response: response, json: nil, error: response.result.error)
            }
            else {
                completionHandler?(success: false, response: response, json: nil, error: response.result.error)
            }
    }

}

/**
 
 Private function to get the CSRF Token
 
{'fraction_non_alphanumeric': 0.09104902639883014, 'fraction_numerical': 0.004463942122681444, 'mean_word_length': 2.6377379619260917, 'pattern_counts': {'":': 8, '<': 17, '<?xml version=': 0, '>': 17, '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': '2997564', 'n_tokens_mistral': 3485, 'n_tokens_neox': 3304, 'n_words': 968}