//
//  ViewController.swift
//  AccessingCloudKitData
//
//  Created by Keith Welch on 1/3/16.
//  Copyright © 2016 Keith Welch. All rights reserved.
//

import UIKit
import CloudKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!
    let cellID = "CellID"
    
    var publicDB: CKDatabase!
    var publicZone: CKRecordZone!
    var customers = [Customer]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let container: CKContainer = CKContainer.defaultContainer()
        publicDB = container.publicCloudDatabase
        publicZone = CKRecordZone.defaultRecordZone()
}

    @IBAction func btnLoadRecords(sender: AnyObject) {
        fetchCustomers()
    }
    
    func fetchCustomers() {
        let predicate: NSPredicate = NSPredicate(value: true)
        let query: CKQuery = CKQuery(recordType: "Customer", predicate: predicate)
        publicDB.performQuery(query, inZoneWithID: nil, completionHandler: {(results, error) -> Void in
            if ((results) != nil) {
                
                self.customers.removeAll()
                for record in results! {
                    
                    let customer: Customer = Customer(record: record as CKRecord, database: self.publicDB)
                    self.customers.append(customer)
                }
                self.tableView.reloadData()
            }
        })
    }
    
    @IBAction func btnAddRecord(sender: AnyObject) {
        let record: CKRecord = CKRecord(recordType: "Customer")
        record["Name"] = "Stephen Vaughn"
        record["Address"] = "25 Center St."
        record["City"] = "Middleton"
        record["State"] = "TX"
        
        self.publicDB.saveRecord(record, completionHandler: {(savedRecord, error) -> Void in
            let recordID: CKRecordID = savedRecord!.recordID
            NSLog("Added RecordID %@", recordID.recordName)
        })
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customers.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
        if cell == nil {
            cell = UITableViewCell(style: .Value1, reuseIdentifier: cellID)
        }

        let customer: Customer = customers[indexPath.row]
        cell!.textLabel!.text = customer.Name
        
        return cell!
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

