//
// TableViewController.swift
// tableviewjson
//
// Created by Jorge Torres A on 4/7/15.
// Copyright (c) 2015 torrestecnologia.com. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
    var TableData: Array < String > = Array < String > ()
    override func viewDidLoad() {
        super.viewDidLoad()
        get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")
    }
    override func numberOfSectionsInTableView(tableView: UITableView) - > Int {
        return 1
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) - > Int {
        return TableData.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel ? .text = TableData[indexPath.row]
        return cell
    }
    func get_data_from_url(url: String) {
        let httpMethod = "GET"
        let timeout = 15
        let url = NSURL(string: url)
        let urlRequest = NSMutableURLRequest(URL: url!,
            cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
            timeoutInterval: 15.0)
        let queue = NSOperationQueue()
        NSURLConnection.sendAsynchronousRequest(
            urlRequest,
            queue: queue,
            completionHandler: {
                (response: NSURLResponse!,
                    data: NSData!,
                    error: NSError!) in
                if data.length > 0 && error == nil {
                    let json = NSString(data: data, encoding: NSASCIIStringEncoding)
                    self.extract_json(json!)
                } else if data.length == 0 && error == nil {
                    println("Nothing was downloaded")
                } else if error != nil {
                    println("Error happened = \(error)")
                }
            }
        )
    }
    func extract_json(data: NSString) {
        var parseError: NSError ?
            let jsonData: NSData = data.dataUsingEncoding(NSASCIIStringEncoding) !
                let json: AnyObject ? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: & parseError)
        if (parseError == nil) {
            if let countries_list = json as ? NSArray {
                for (var i = 0; i < countries_list.count; i++) {
                    if let country_obj = countries_list[i] as ? NSDictionary {
                        if let country_name = country_obj["country"] as ? String {
                            if let country_code = country_obj["code"] as ? String {
                                TableData.append(country_name + " [" + country_code + "]")
                            }
                        }
                    }
                }
            }
        }
        do_table_refresh();
    }
    func do_table_refresh() {
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.reloadData()
            return
        })
    }
}