<commit_before>//
//  HTTPHelper.swift
//  RevCheckIn
//
//  Created by <NAME> on 7/29/14.
//  Copyright (c) 2014 <NAME>. All rights reserved.
//

import UIKit
import Foundation
import CoreData

class HTTPHelper: NSObject {

    func deleteActiveUser(){
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let freq = NSFetchRequest(entityName: "Active_user")
        
        var myList: Array<AnyObject> = []
        myList = context.executeFetchRequest(freq, error: nil)!
        if !myList.isEmpty{
            println("deleting context")
            for item in myList {
                context.deleteObject(item as NSManagedObject)
            }
            context.save(nil)
        }
    }
    
    func deleteActiveDevice(){
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let freq = NSFetchRequest(entityName: "User_device")
        
        var myList: Array<AnyObject> = []
        myList = context.executeFetchRequest(freq, error: nil)!
        if !myList.isEmpty{
            println("deleting context")
            for item in myList {
                context.deleteObject(item as NSManagedObject)
            }
        }
        context.save(nil)
    }
    
    func setUserContext(username:String) {
        
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("Active_user", inManagedObjectContext: context)
        
        var newItem = activeUserModel(entity: en!, insertIntoManagedObjectContext: context)
        newItem.username = (username as NSString).lowercaseString
        context.save(nil)
    }
    
    func setDeviceContext(device:String) {
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("User_device", inManagedObjectContext: context)
        
        var newItem = userDeviceModel(entity: en!, insertIntoManagedObjectContext: context)
        newItem.device = device
        context.save(nil)
    }
    
    func getDeviceContext()->String{
        var myList: Array<AnyObject> = []
        var appDel2: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var context2: NSManagedObjectContext = appDel2.managedObjectContext!
        var freq = NSFetchRequest(entityName: "User_device")
        while myList.isEmpty{myList = context2.executeFetchRequest(freq, error: nil)!}
        var selectedItem: NSManagedObject = myList[0] as NSManagedObject
        return selectedItem.valueForKeyPath("device") as String
    }
    
    func login(username:String, password:String){
        var params = ["PUSH_ID":"123", "username":username, "password":password, "call":"login"] as Dictionary
        var request = HTTPTask()
        self.deleteActiveUser()
        request.GET("http://experiencepush.com/rev/rest/", parameters: params, success: {(response: HTTPResponse) -> Void in
            if response.responseObject != nil {
                let data = response.responseObject as NSData
                let datastring = NSString(data: data, encoding: NSUTF8StringEncoding)
                if datastring == "1" {
                    println("success")
                    self.setUserContext(username);
                }else {	
                    println("failure")
                    self.setUserContext("-1")
                }
            }
            },failure: {(error: NSError) -> Void in
                println("error: \(error)")
                self.setUserContext("-1")
        })
        println("done")
    }
    
    func register(username:String, password:String, name:String, email:String, registrationCode:String, role:String, phone:String) {
        Crashlytics.setObjectValue("register", forKey: "HTTPHelperAction")
        let params = ["PUSH_ID":"123", "username":username, "password":password, "name":name, "email":email, "code":registrationCode,"role":role,"phone":phone, "call":"addNewUser"] as Dictionary
        var request = HTTPTask()
        self.deleteActiveUser()
        request.POST("http://experiencepush.com/rev/rest/index.php", parameters: params, success: {(response: HTTPResponse) -> Void in
                let datastring:String = NSString(data:response.responseObject! as NSData, encoding:NSUTF8StringEncoding)<commit_msg>new device registration code. TODO: Test registration device id token synchronization database side.<commit_after>//
//  HTTPHelper.swift
//  RevCheckIn
//
//  Created by <NAME> on 7/29/14.
//  Copyright (c) 2014 <NAME>. All rights reserved.
//

import UIKit
import Foundation
import CoreData

class HTTPHelper: NSObject {

    func deleteActiveUser(){
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let freq = NSFetchRequest(entityName: "Active_user")
        
        var myList: Array<AnyObject> = []
        myList = context.executeFetchRequest(freq, error: nil)!
        if !myList.isEmpty{
            println("deleting context")
            for item in myList {
                context.deleteObject(item as NSManagedObject)
            }
            context.save(nil)
        }
    }
    
    func deleteActiveDevice(){
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let freq = NSFetchRequest(entityName: "User_device")
        
        var myList: Array<AnyObject> = []
        myList = context.executeFetchRequest(freq, error: nil)!
        if !myList.isEmpty{
            println("deleting context")
            for item in myList {
                context.deleteObject(item as NSManagedObject)
            }
        }
        context.save(nil)
    }
    
    func setUserContext(username:String) {
        
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("Active_user", inManagedObjectContext: context)
        
        var newItem = activeUserModel(entity: en!, insertIntoManagedObjectContext: context)
        newItem.username = (username as NSString).lowercaseString
        context.save(nil)
    }
    
    func setDeviceContext(device:String) {
        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("User_device", inManagedObjectContext: context)
        
        var newItem = userDeviceModel(entity: en!, insertIntoManagedObjectContext: context)
        newItem.device = device
        context.save(nil)
    }
    
    func getDeviceContext()->String{
        var myList: Array<AnyObject> = []
        var appDel2: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var context2: NSManagedObjectContext = appDel2.managedObjectContext!
        var freq = NSFetchRequest(entityName: "User_device")
        while myList.isEmpty{myList = context2.executeFetchRequest(freq, error: nil)!}
        var selectedItem: NSManagedObject = myList[0] as NSManagedObject
        return selectedItem.valueForKeyPath("device") as String
    }
    
    func login(username:String, password:String){
        var params = ["PUSH_ID":"123", "username":username, "password":password, "call":"login"] as Dictionary
        var request = HTTPTask()
        self.deleteActiveUser()
        request.GET("http://experiencepush.com/rev/rest/", parameters: params, success: {(response: HTTPResponse) -> Void in
            if response.responseObject != nil {
                let data = response.responseObject as NSData
                let datastring = NSString(data: data, encoding: NSUTF8StringEncoding)
                if datastring == "1" {
                    println("success")
                    self.setUserContext(username);
                }else {	
                    println("failure")
                    self.setUserContext("-1")
                }
            }
            },failure: {(error: NSError) -> Void in
                println("error: \(error)")
                self.setUserContext("-1")
        })
        println("done")
    }
    
    func register(username:String, password:String, name:String, email:String, registrationCode:String, role:String, phone:String) {
        
        // get user device id token and check for a nil case. If nill, set device to -1(error) state.
        var device_id_data: String? = CoreDataHelper().getUserId()
        var device_id:String = ""
        if let data = device_id_data {
            device_id = data
        }else{
            device_id = "-1"
        }
        
        Crashlytics.setObjectValue("register", forKey: "HTTPHelperAction")
        
        // HTTP POST parameters
        let params = ["PUSH_ID":"123", "username":username, "password":password, "name":name, "email":email, "code":registrationCode,"role":role,"phone":phone, "call":"addNewUser", "device_id": device_id] as Dictionary
        var request = HTTPTask()
        self.deleteActiveUser()
        request.POST("http://experiencepush.com/rev/rest/index.php", parameters: params, success: {(response: HTTPResponse) -> Void in
                let datastring:String = NSString(data:response.responseObject! as NSData, encoding:NSUTF8StringEncoding)
{'fraction_non_alphanumeric': 0.10027264465313541, 'fraction_numerical': 0.005250934060385742, 'mean_word_length': 2.608014571948998, 'pattern_counts': {'":': 27, '<': 13, '<?xml version=': 0, '>': 21, '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': '329725', 'n_tokens_mistral': 2640, 'n_tokens_neox': 2563, 'n_words': 601}