/*
 *  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 BeaconDeviceMonitorView: UIViewController {

    
    @IBOutlet var SeventhViewOutlet: UIView!
    
    @IBOutlet weak var appNameLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceNameLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceIdLabelOutlet: UILabel!
    
    @IBOutlet weak var deviceUUIDLabelOutlet: UILabel!
    
    @IBOutlet weak var beaconMajorLabelOutlet: UILabel!
    
    @IBOutlet weak var beaconMinorLabelOutlet: UILabel!
    
    @IBOutlet weak var signalStrengthLabelOutlet: UILabel!
    
    @IBOutlet weak var measuredSignalLabelOutlet: UILabel!
    
    @IBOutlet weak var receivedSignalLabelOutlet: 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()
        SeventhViewOutlet.backgroundColor = UIColor(patternImage: image)
        
        for dev in activeDevices {
            if dev.getEndpointId() == monitoredDevice {
                virtualDevice = dev
            }
        }
        
        // Monitor the selected device for iBeacon device model and update the 
        // UI view accordingly.
        if virtualDevice != nil {
            
            // iBeacon 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
                    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 = kCurBeaconValue
        
        self.deviceIdLabelOutlet.text = monitoredDevice
        
        self.deviceUUIDLabelOutlet.text = "UUID: \(monitoredDeviceUUID)"
        self.beaconMajorLabelOutlet.text = "Major: \(monitoredDeviceMajor)"
        self.beaconMinorLabelOutlet.text = "Minor: \(monitoredDeviceMinor)"
        
        for dev in activeDevices {
            if dev.getEndpointId() == monitoredDevice {
                virtualDevice = dev
            }
        }
        
        self.signalStrengthLabelOutlet.text = "Signal Strength"
        do {
            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
            }
        }
        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)
    }
}
