//
//  SelectDeviceTableViewController.swift
//  NeoSpectraMicroSwift
//
//  Created by Si-Ware on 11/15/17.
//  Copyright © 2017 siware. All rights reserved.
//

import UIKit
//import CoreBluetooth

class DevicesOptions{
    var name : String
    init?(name: String) {
        
        // Initialization should fail if there is no name or if the rating is negative.
        if name.isEmpty {
            return nil
        }
        
        // Initialize stored properties.
        self.name = name
        
    }
}

class SelectDeviceTableViewController: UITableViewController{

    var Devices = [DevicesOptions]()
    var timer            : Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }
        statusBar.backgroundColor = UIColor.clear
        // 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
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(SelectDeviceTableViewController.dismiss as (SelectDeviceTableViewController) -> () -> ()))
        let activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityView.startAnimating()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: activityView)
        
        let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height))
        let messageLabel = UILabel(frame: rect)
        messageLabel.text = "No Devices Found"
        messageLabel.textColor = UIColor.black
        messageLabel.numberOfLines = 0;
        messageLabel.textAlignment = .center;
        messageLabel.font = messageLabel.font.withSize(17.0)
        messageLabel.sizeToFit()
        tableView.backgroundView = messageLabel
        
        
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
        
        //self.loadDevices()
        
        tableView.tableFooterView = UIView()
    }

    func dismiss() {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func timerFire() {
            if (HomeViewController.peripherals?.count)! > 0 {
                Devices.removeAll()
                for peripheral in HomeViewController.peripherals!{
                    let p = peripheral as! NSScannedPeripheral
                    if(p.name().contains("NeoSpectraMicro")){
                        guard let Devices1 = DevicesOptions(name: p.name())
                            else {
                                fatalError("Unable to instantiate Devices1")
                            }
                        Devices += [Devices1]
                    }
                }
                self.tableView.backgroundView = nil
                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 Devices.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "SelectDeviceTableViewCell"
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SelectDeviceTableViewCell
            else {
                fatalError("The dequeued cell is not an instance of SelectDeviceTableViewCell.")
        }
        
        // Fetches the appropriate meal for the data source layout.
        let DevicesOption = Devices[indexPath.row]
        
        cell.nameLabel.text = DevicesOption.name
        cell.nameLabel.sizeToFit()
        
        return cell
       
    }

    /*
    // 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
    }
    */
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
        let alertController = UIAlertController(title: "Start Connection", message:
            "Connect to " + self.Devices[indexPath.row].name + " ?", preferredStyle: UIAlertControllerStyle.alert)
        
        alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
            Constants.WaitToStartBluetoothConnection = false
            Constants.SelectedDeviceName = self.Devices[indexPath.row].name
            self.dismiss()
        }))
        
        alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
            tableView.deselectRow(at: indexPath, animated: true)
        }))
        
        DispatchQueue.main.async {
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
