//
//  ViewController.swift
//  Json
//
//  Created by Keith Welch on 9/19/15.
//  Copyright © 2015 Keith Welch. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    let cellID = "CellID"

    var places:NSMutableArray!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        places = NSMutableArray()
        tableView.dataSource = self
    }

    @IBAction func btnReadJsonTouched(sender: AnyObject) {

        let path = NSBundle.mainBundle().pathForResource("places", ofType: "json")
        do {
        let jsonData = try NSData(contentsOfFile: path!, options: .DataReadingMappedIfSafe)
            
        // you can create JSON objects with the method NSJSONSerialization.dataWithJSONObject
        let jsonResult: NSDictionary = try (NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary)!
            if let array : NSArray = jsonResult["places"] as? NSArray
            {
                places = NSMutableArray()
                // Iterate through the array of dictionaries
                for dictionary in array {
                    // Create a new Place object with information in the dictionary
                    let place:Place = Place()
                    place.initWithJSONDictionary(dictionary as! NSDictionary)
                    // Add the Place object to the array
                    places.addObject(place)
                }
                tableView.reloadData()
            }
        }
        catch let error as NSError {
            NSLog(error.description)
        }
    }
    

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return places.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let place:Place = places[indexPath.row] as! Place
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
        if cell == nil {
            cell = UITableViewCell(style: .Value1, reuseIdentifier: cellID)
        }
        cell!.textLabel!.text = place.title
        cell!.detailTextLabel!.text = String(format:"%@ - %@, %@", place.city, place.latitude, place.longitude)

        return cell!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

