//
//  RoomsController.swift
//  Home
//
//  Created by Richard Kuckovsky on 22.4.17.
//  Copyright © 2017 Richard Kuckovsky. All rights reserved.
//

import UIKit

class RoomsController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.refreshControl?.addTarget(self, action: #selector(AvailableDevicesViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged)

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        SocketIOManager.sharedInstance.listRooms(completionHandler: { (ok) in
            
            self.tableView.reloadData()
            
        })
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rooms.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

            cell?.textLabel?.text = rooms[indexPath.row].name

        return cell!
    }
    
    func handleRefresh(_ refreshControl: UIRefreshControl) {
        
        SocketIOManager.sharedInstance.listRooms(completionHandler: { (ok) in
            
            self.tableView.reloadData()
            refreshControl.endRefreshing()
            
        })
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier != "add_room") {
            let dest = segue.destination as! RoomController
            let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow! as NSIndexPath
        
            print(rooms[indexPath.row].outputs)
        
            dest.outputs = rooms[indexPath.row].outputs
            dest.sensors = rooms[indexPath.row].sensors
            dest.events = rooms[indexPath.row].events
            dest.room = rooms[indexPath.row].id
        }
        
        
    }
    

}
