/*
 *  Copyright © 2016 Oracle and/or its affiliates. All rights reserved.
 *  This software is dual-licensed to you under the MIT License (MIT) and
 *  the Universal Permissive License (UPL). See the LICENSE file in the root
 *  directory for license terms. You may choose either license, or both.
 */

import UIKit

class BeaconSelectionView: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var SecondView: UIView!
    
    @IBOutlet weak var headLineLabelOutlet: UILabel!
    
    
    @IBOutlet weak var selectBeaconLabelOutlet: UILabel!
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.tableView.register(UITableViewCell.self,
                                forCellReuseIdentifier: "cell")
    }
    
    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        var count = 0
        beaconList.sort(by: Beacon.sort)
        for b in beaconList {
            if b.getDistance() <= DataConnector.getMaxDistance() {
                count += 1
            }
            else {
                break
            }
        }
        return count
    }
    
    // Fill the table view with device models.
    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: DeviceSelectionCell = self.tableView.dequeueReusableCell(
            withIdentifier: DeviceSelectionCell.ID) as! DeviceSelectionCell
        cell.beaconInfo.textAlignment = NSTextAlignment.left

        let hardId = beaconList[indexPath.row].getHardwareId()
        let distance = beaconList[indexPath.row].getDistance()
        if (distance != -1) {
            cell.beaconInfo.text = hardId +
                String(format: " \n  %.3f meters away", distance)
        } else {
            cell.beaconInfo.text = hardId + " \n  Distance unknown"
        }
        cell.beaconInfo.adjustsFontSizeToFitWidth = true
        
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        
        return cell
    }
    
    func tableView(_ tableView: UITableView,
                   didSelectRowAt indexPath: IndexPath) {
        self.tableView.cellForRow(at: indexPath)?.selectionStyle = .gray
        self.showBeacon(index: indexPath.row)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear (_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.setHidesBackButton(true, animated: false)
        
        self.headLineLabelOutlet.font = .boldSystemFont(ofSize: 18.0)
        self.headLineLabelOutlet.text = kGWwvHeadline
        
        self.selectBeaconLabelOutlet.textAlignment = .center
        self.selectBeaconLabelOutlet.text = kGWSecodLineSelect
        
        UIGraphicsBeginImageContext(CGSize(width: self.view.frame.size.width,
                                           height: self.view.frame.size.width - 18))
        UIImage(named: "cloudes-sw.png")?.drawAsPattern(in: self.view.bounds)
        let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        self.SecondView.backgroundColor = UIColor(patternImage: image)
        
        if dataConnector == nil {
            do {
                try dataConnector = DataConnector()
            } catch {
                showError(controller: self, alertTitle: "Provisioning Failure",
                          message: kProvisioningFailure, actionTitle: "OK",
                          handler: { (action: UIAlertAction!) -> () in
                    // Ensure that user can re-provision the device
                    removeLastSettingsFile()
                    self.navigationController?.popToRootViewController(animated: false)
                })
            }
            
            if dataConnector != nil {
                // Prepare and activate the gateway device
                dataConnector!.pgd(callback: { error in
                    if error == nil {
                        if !dataConnector!.isDeviceInitialized() {
                            DispatchQueue.main.async() {
                                showError(controller: self,
                                          alertTitle: "Device Initialization Alert",
                                          message: dataConnector!.getErrorMessage(),
                                          actionTitle: "Exit App",
                                    handler: { (action: UIAlertAction?) -> () in
                                        exit(0)})
                            }
                        } else {
                            dataConnector!.unstop()
                            DispatchQueue.main.async() {
                                timer1 = Timer.scheduledTimer(timeInterval: 5.0,
                                    target: self,
                                    selector: #selector(BeaconSelectionView.updateData),
                                    userInfo: nil, repeats: true)
                                // Create and manage the indirectly connected devices.
                                dataConnector!.startSample()
                            }
                        }
                    } else {
                        DispatchQueue.main.async() {
                            showError(controller: self,
                                  alertTitle: "Device Initialization Alert: \(String(describing: error))",
                                  message: dataConnector!.getErrorMessage(),
                                  actionTitle: "Exit App",
                                  handler: { (action: UIAlertAction?) -> () in
                                    exit(0)})
                        }

                    }
                })
            }
        } else {
            // Current view is loaded after touch the Back button in next view 
            // (DeviceDetailView)
            dataConnector!.unstop()
            dataConnector!.startLoop()
            DispatchQueue.main.async() {
                timer1 = Timer.scheduledTimer(timeInterval: 5.0, target: self,
                                selector: #selector(BeaconSelectionView.updateData),
                                userInfo: nil, repeats: true)
            }
        }
    }
    
    override func viewDidAppear (_ animated: Bool) {
        super.viewDidAppear(animated)
        
        self.tableView.flashScrollIndicators()
    }
    
    // Action for one row selection. Active devices are got according to the 
    // selected device model.
    @objc func showBeacon(index: Int) {
        selectedBeacon = beaconList[index]
        let thirdViewController = self.storyboard?.instantiateViewController(
            withIdentifier: "DeviceDetailView") as! DeviceDetailView
        self.navigationController?.pushViewController(thirdViewController,
                                                      animated: true)
    }
    
    @objc func updateData() {
        if(!stopped) {
            self.tableView.reloadData()
        }
    }
}

// Define custom table view cell
class DeviceSelectionCell : UITableViewCell {
    @objc static let ID = "DeviceCell"
    
    @IBOutlet weak var beaconInfo: UILabel!
}
