/*
 *  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
import EnterpriseLib

class EddystoneDeviceMonitorView: UIViewController {

    @IBOutlet var EighthViewOutlet: UIView!
    
    @IBOutlet weak var appNameLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceNameLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceIdLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceNamespaceLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceInstanceLabelOutlet: UILabel!
    
    @IBOutlet weak var signalStrengthLabelOutlet: UILabel!
    
    @IBOutlet weak var measuredSignalLabelOutlet: UILabel!
    
    @IBOutlet weak var receivedSignalLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceTelemetryLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceTempLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceVoltageLabelOutlet: UILabel!
    
    @IBOutlet weak var backToViewController4: UIButton! {
        didSet {
            backToViewController4.layer.cornerRadius = 6.0
            backToViewController4.layer.borderColor = UIColor.lightGray.cgColor
            backToViewController4.layer.borderWidth = 1.0
            backToViewController4.layer.backgroundColor = UIColor(white: 0.90,
                                                                  alpha: 1.0).cgColor
        }
    }
    
    
    var virtualDevice: VirtualDevice?
    
    @objc var idx = 0
    @objc var cvs: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        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()
        EighthViewOutlet.backgroundColor = UIColor(patternImage: image)
        
        for dev in activeDevices {
            if dev.getEndpointId() == monitoredDevice {
                virtualDevice = dev
            }
        }
        
        // Monitor the selected device for Eddystone Beacon device model and 
        // update the UI view accordingly.
        if virtualDevice != nil {
            
            // Eddystone Beacon values changes are managed.
            virtualDevice?.setOnChange(callback: { (event: ChangeEvent) in
                DispatchQueue.main.async(execute: {
                var namedValue = event.getNamedValue()
                var hasMore = true
                
                repeat  {
                    switch namedValue.getName() {
                    case "ora_rssi":
                        rssi = namedValue.getValue()!.doubleValue
                        self.cvs[self.idx] = String(format: "%.1f", rssi)
                        self.receivedSignalLabelOutlet.text =
                            "Received: \(self.cvs[self.idx])"
                        break
                    case "ora_txPower":
                        mssi = namedValue.getValue()!.intValue
                        self.measuredSignalLabelOutlet.text =
                            "Measured: \(mssi.description)"
                        break
                    case "temperature":
                        temperature = namedValue.getValue()!.doubleValue
                        let celsiusTemp = temperature / 256.0
                        self.deviceTempLabelOutlet.text =
                            String(format: "Temperature %.3f \u{00B0}C",
                                   celsiusTemp)
                        break
                    case "batteryVoltage":
                        voltage = namedValue.getValue()!.doubleValue
                        let voltValue = voltage / 1000.0
                        self.deviceVoltageLabelOutlet.text =
                            String(format: "Battery Voltage %.3f V", voltValue)
                        break
                    default:
                        break
                    }
                    
                    if (namedValue.next() != nil) {
                        namedValue = namedValue.next()!
                    }
                    else {
                        hasMore = false
                    }
                }
                while (hasMore)
                })
            })
        }
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear (_ animated: Bool) {
        self.navigationItem.setHidesBackButton(true, animated: false)
        
        self.appNameLabelOutlet.font = .boldSystemFont(ofSize: 18.0)
        self.appNameLabelOutlet.text = kEnterpriseHeadLine
        
        self.deviceNameLabelOutlet.text = kCurEddyValue
        
        self.deviceIdLabelOutlet.text = monitoredDevice
        
        let tokens = monitoredDeviceUUID.components(separatedBy: ":")
        self.deviceNamespaceLabelOutlet.text = "Namespace: \(tokens[0])"
        self.deviceInstanceLabelOutlet.text =
                                "Instance: \(monitoredDeviceSerialNumber)"
        
        for dev in activeDevices {
            if dev.getEndpointId() == monitoredDevice {
                virtualDevice = dev
            }
        }
        
        do {
            self.signalStrengthLabelOutlet.text = "Signal Strength"
            
            let power = try Int(truncating:virtualDevice?.get(attributeName: "ora_txPower") as! NSNumber)
            self.measuredSignalLabelOutlet.text = "Measured: \(power.description)"
            
            let userDefaults = UserDefaults.standard
            self.cvs = userDefaults.array(forKey: "currentValues") as! [String]
            let ids = userDefaults.array(forKey: "idValues") as! [String]
            userDefaults.synchronize()
            
            let vdId = virtualDevice?.getEndpointId()
            for devId in ids {
                if devId == vdId {
                    self.receivedSignalLabelOutlet.text =
                                            "Received: \(self.cvs[self.idx])"
                    break
                }
                self.idx += 1
            }
            
            self.deviceTelemetryLabelOutlet.text = "Telemetry Data"
            try self.deviceTempLabelOutlet.text =
                String(format: "Temperature %.3f \u{00B0}C",
                       (virtualDevice?.get(attributeName: "temperature")?.doubleValue)! / 256.0)

            
            try self.deviceVoltageLabelOutlet.text =
                String(format: "Battery Voltage %.3f V",
                       (virtualDevice?.get(attributeName: "batteryVoltage")?.doubleValue)! / 1000.0)
        }
        catch { }
    }
    

    @IBAction func onBackButtonClick(_ sender: AnyObject) {
        let userDefaults = UserDefaults.standard
        userDefaults.set(self.cvs, forKey: "currentValues")
        userDefaults.synchronize()
        
        DeviceSelectionView.first = false
        
        let fourthViewController = self.storyboard?.instantiateViewController(
            withIdentifier: "DeviceSelectionView") as! DeviceSelectionView
        self.navigationController?.pushViewController(fourthViewController,
                                                      animated: false)
    }
    

}
