//
//  AvailableDevicesViewController.swift
//  Home
//
//  Created by Richard Kuckovsky on 13.5.17.
//  Copyright © 2017 Richard Kuckovsky. All rights reserved.
//

import UIKit

class AvailableDeviceCellController: UITableViewCell {
    
    @IBOutlet weak var lbl_name: UILabel!
    var id = 0
    var indexPath = IndexPath()
    
    var availableDelegate: availableDeviceCellDelegate?
    
    @IBAction func activate(_ sender: Any) {
        if let delegate = availableDelegate {
            delegate.activateTapped(id: id, indexPath: indexPath) { (done: Bool) -> Void in
            }
        }
    }
    
}

protocol availableDeviceCellDelegate {
    func activateTapped(id: Int, indexPath: IndexPath, completionHandler: @escaping (_ status: Bool) -> Void)
}

class AvailableDevicesViewController: UITableViewController, availableDeviceCellDelegate {
    
    var names = [String]()
    var ids = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.refreshControl?.addTarget(self, action: #selector(AvailableDevicesViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged)
        
        SocketIOManager.sharedInstance.loadUnusedDevices(completionHandler: { (names, ids) in
            self.names = names
            self.ids = ids
            
            self.tableView.reloadData()
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return ids.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "device", for: indexPath) as? AvailableDeviceCellController

        if cell?.availableDelegate == nil {
            cell?.availableDelegate = self
        }
        cell?.indexPath = indexPath as IndexPath
        // Configure the cell...
        cell?.lbl_name.text = "[" + String(ids[indexPath.row]) + "] " + names[indexPath.row]
        cell?.id = ids[indexPath.row]

        return cell!
    }
    
    func handleRefresh(_ refreshControl: UIRefreshControl) {
        
        SocketIOManager.sharedInstance.loadUnusedDevices(completionHandler: { (names, ids) in
            self.names = names
            self.ids = ids
            
            self.tableView.reloadData()
            
            refreshControl.endRefreshing()
        })
    }
    
    
    internal func activateTapped(id: Int, indexPath: IndexPath, completionHandler: @escaping (_ status: Bool) -> Void) {
        SocketIOManager.sharedInstance.activateDevice(id: id) { (status) in
            if(status) {
                self.names.remove(at: indexPath.row)
                self.ids.remove(at: indexPath.row)
                self.tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.left)

            } else {
                let alert = UIAlertController(title: "Chyba", message: "Zariadenie sa nepodarilo aktivovať", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
            completionHandler(status)
        }
        
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
