 //
 //  Created by Mobin Zadeh Kochak on 04/09/2015.
 //  Copyright (c) 2015 Mobin Zadeh Kochak. All rights reserved.
+//  Edited by Mason Phillips (https://github.com/mathmatrix828/
+//  Edited on 30MAY2016
 //
 
 import UIKit

    - lol-status-v1.0
    */
}

public class lolApiWrapper: NSObject {
    
    // MARK: Initialised detail
    var APIKey: String!
    var region: String?
    var miniURL: String!
    var result: NSDictionary!
    var static_data: Bool = false
    private var debugEnabled: Bool = false
    
    var delegate: LolAPIListener?
    var sharedInstance: lolApiWrapper = lolApiWrapper()
    
    public func ApiKey(APIKey: String, region: String?) -> lolApiWrapper {
        self.APIKey = APIKey
        self.region = region
        
        return self
    }
    
    public func APIWithDebug(APIKey k: String, region r: String?) -> lolApiWrapper {
        debugEnabled = true
        
        return ApiKey(k, region: r)
    }
    
    // MARK: Retrieve API
    public func get() -> NSDictionary {
        guard let r = region else {
            for r in 0..<regions.count {
                let finalURL = genURL(forRegion: regions[r])
                result = getJSON(finalURL)
                if result.count > 0 {
                    break
                }
            }
            return result
        }
        
        let finalURL = genURL(forRegion: r)
        result = getJSON(finalURL)
        
        if debugEnabled { print(result) }
        delegate?.didReturnResult(result)
        
        return result
    }
    
    private func genURL(forRegion r: String) -> String {
        let apiURL = ((static_data) ? APIURL : STATICURL).stringByReplacingOccurrencesOfString("{region}", withString: r, options: NSStringCompareOptions.LiteralSearch)
        
        let operand = ((miniURL.containsString("?")) ? "&" : "?")
        let finalURL = "\(apiURL)\(miniURL)\(operand)api_key=\(APIKey)"
        
        return finalURL
    }
    
    public func getJSON(urlToRequest: String) -> NSDictionary{
