<commit_before>//
//  WhartonGSRNetworkManager.swift
//  PennMobile
//
//  Created by <NAME> on 1/20/19.
//  Copyright © 2019 PennLabs. All rights reserved.
//

import Foundation
import SwiftyJSON

class WhartonGSRNetworkManager: NSObject, Requestable {
    
    static let instance = WhartonGSRNetworkManager()
    
    let availUrl = "https://apps.wharton.upenn.edu/gsr/api/app/grid_view"
    let availUrlNoSessionID = "https://api.pennlabs.org/studyspaces/gsr"
    let bookURL = "https://apps.wharton.upenn.edu/gsr/reserve"
    
    func getAvailability(sessionID: String?, date: GSRDate, callback: @escaping ((_ rooms: [GSRRoom]?) -> Void)) {
        if sessionID == nil {
            getAvailabilityWithoutSessionID(date: date, callback: callback)
            return
        }
        
        let urlStr = "\(availUrl)/?search_time=\(date.string)%2005:00&building_code=1"
        let url = URL(string: urlStr)!
        var request = URLRequest(url: url)
        
        request.httpMethod = "GET"
        let sessionCookie = "sessionid=\(sessionID!)"
        request.addValue(sessionCookie, forHTTPHeaderField: "Cookie")
        let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
            if error != nil {
                // indicates that user is unable to connect to internet
                callback(nil)
            } else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    if let data = data, let _ = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                        if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
                            //data recieved and parsed successfully
                            if let dict = json {
                                let json = JSON(dict)
                                let rooms = try? self.parseAvailabilityJSON(json)
                                callback(rooms)
                            }
                            return
                        }
                    }
                }
                UserDefaults.standard.clearSessionID()
                self.getAvailabilityWithoutSessionID(date: date, callback: callback)
            }
            
        })
        task.resume()
    }
    
    func getAvailabilityWithoutSessionID(date: GSRDate, callback: @escaping ((_ rooms: [GSRRoom]?) -> Void)) {
        let url = "\(availUrlNoSessionID)?date=\(date.string)"
        getRequest(url: url) { (dict, _, _) in
            var rooms: [GSRRoom]? = nil
            if let dict = dict {
                let json = JSON(dict)
                rooms = try? self.parseAvailabilityJSON(json)
            }
            callback(rooms)
        }
    }
    
    func bookRoom(booking: GSRBooking, callback: @escaping ((_ success: Bool, _ errorMsg: String?) -> Void)) {
        let sessionID: String = booking.sessionId
        let urlStr = getBookingUrl(for: booking)
        let url = URL(string: urlStr)!
        var request = URLRequest(url: url)
        
        request.httpMethod = "GET"
        let sessionCookie = "sessionid=h137cblz2nvlk8yky17smamr3npntoyw"//"sessionid=\(sessionID!)"<commit_msg>bug fix<commit_after>//
//  WhartonGSRNetworkManager.swift
//  PennMobile
//
//  Created by <NAME> on 1/20/19.
//  Copyright © 2019 PennLabs. All rights reserved.
//

import Foundation
import SwiftyJSON

class WhartonGSRNetworkManager: NSObject, Requestable {
    
    static let instance = WhartonGSRNetworkManager()
    
    let availUrl = "https://apps.wharton.upenn.edu/gsr/api/app/grid_view"
    let availUrlNoSessionID = "https://api.pennlabs.org/studyspaces/gsr"
    let bookURL = "https://apps.wharton.upenn.edu/gsr/reserve"
    
    func getAvailability(sessionID: String?, date: GSRDate, callback: @escaping ((_ rooms: [GSRRoom]?) -> Void)) {
        if sessionID == nil {
            getAvailabilityWithoutSessionID(date: date, callback: callback)
            return
        }
        
        let urlStr = "\(availUrl)/?search_time=\(date.string)%2005:00&building_code=1"
        let url = URL(string: urlStr)!
        var request = URLRequest(url: url)
        
        request.httpMethod = "GET"
        let sessionCookie = "sessionid=\(sessionID!)"
        request.addValue(sessionCookie, forHTTPHeaderField: "Cookie")
        let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
            if error != nil {
                // indicates that user is unable to connect to internet
                callback(nil)
            } else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    if let data = data, let _ = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                        if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
                            //data recieved and parsed successfully
                            if let dict = json {
                                let json = JSON(dict)
                                let rooms = try? self.parseAvailabilityJSON(json)
                                callback(rooms)
                            }
                            return
                        }
                    }
                }
                UserDefaults.standard.clearSessionID()
                self.getAvailabilityWithoutSessionID(date: date, callback: callback)
            }
            
        })
        task.resume()
    }
    
    func getAvailabilityWithoutSessionID(date: GSRDate, callback: @escaping ((_ rooms: [GSRRoom]?) -> Void)) {
        let url = "\(availUrlNoSessionID)?date=\(date.string)"
        getRequest(url: url) { (dict, _, _) in
            var rooms: [GSRRoom]? = nil
            if let dict = dict {
                let json = JSON(dict)
                rooms = try? self.parseAvailabilityJSON(json)
            }
            callback(rooms)
        }
    }
    
    func bookRoom(booking: GSRBooking, callback: @escaping ((_ success: Bool, _ errorMsg: String?) -> Void)) {
        let sessionID: String = booking.sessionId
        let urlStr = getBookingUrl(for: booking)
        let url = URL(string: urlStr)!
        var request = URLRequest(url: url)
        
        request.httpMethod = "GET"
        let sessionCookie = "sessionid=\(sessionID)"
{'fraction_non_alphanumeric': 0.10136691752418983, 'fraction_numerical': 0.007372139456304715, 'mean_word_length': 1.806896551724138, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1693090', 'n_tokens_mistral': 1863, 'n_tokens_neox': 1757, 'n_words': 420}