Files
POCloud-iOS/pocloud/Controller/ChannelDetailViewController.swift
2018-06-01 11:29:47 -05:00

162 lines
6.6 KiB
Swift

//
// ChannelDetailViewController.swift
// pocloud
//
// Created by Patrick McDonagh on 5/25/18.
// Copyright © 2018 patrickjmcd. All rights reserved.
//
import UIKit
import RealmSwift
import SwiftyJSON
import PromiseKit
import Alamofire
import SVProgressHUD
import FirebaseDatabase
class ChannelDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let realm = try! Realm()
var ref : DatabaseReference!
let baseURL = (UIApplication.shared.delegate as! AppDelegate).baseURL
let user = (UIApplication.shared.delegate as! AppDelegate).user
let channelDataTypes = (UIApplication.shared.delegate as! AppDelegate).channelDataTypes
let formatter = DateFormatter()
var thisDevice : Device?
var thisChannel : Channel?
var channelHistory : [ChannelHistoryValue] = [ChannelHistoryValue]()
@IBOutlet weak var deviceNameLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var helpDescriptionLabel: UILabel!
@IBOutlet weak var meshifyNameLabel: UILabel!
@IBOutlet weak var dataTypeLabel: UILabel!
@IBOutlet weak var historyTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
historyTableView.delegate = self
historyTableView.dataSource = self
setupChannelDisplay()
SVProgressHUD.show()
ref = Database.database().reference()
let macAddress = String((thisDevice?.macAddress.replacingOccurrences(of: ":", with: "").uppercased().dropLast(4))!)
let deviceTypeName = (thisDevice?.parentDeviceType.first?.name)!
let channelName = thisChannel?.name
firstly {
getFirebaseChannelHistory(deviceMacAddress: macAddress, deviceTypeName: deviceTypeName, channelName: channelName!)
}.done { (hist) in
self.channelHistory = hist
self.historyTableView.reloadData()
SVProgressHUD.dismiss()
self.ref.removeAllObservers()
}.catch { error in
print("Error in ChannelDetailViewController promise: \(error)")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "openHistoryGraph" {
let destinationVC = segue.destination as! HistoryGraphViewController
destinationVC.channelHistory = channelHistory
destinationVC.thisChannel = thisChannel
}
}
//MARK: - TABLE METHODS
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return channelHistory.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "channelHistoryCell", for: indexPath) as! ChannelHistoryCell
if let timestamp = channelHistory[indexPath.row].timestamp {
cell.timestampLabel.text = formatter.string(from: timestamp)
} else {
cell.timestampLabel.text = "Error"
}
cell.valueLabel.text = channelHistory[indexPath.row].value
return cell
}
//MARK: - ChannelDefinition Methods
func setupChannelDisplay(){
deviceNameLabel.text = thisDevice?.vanityName ?? "Unknown"
nameLabel.text = thisChannel?.subTitle ?? "Unknown"
helpDescriptionLabel.text = thisChannel?.helpExplanation ?? "Unknown"
meshifyNameLabel.text = thisChannel?.name ?? "Unknown"
dataTypeLabel.text = channelDataTypes[thisChannel?.dataType ?? 0]
self.navigationItem.rightBarButtonItem?.isEnabled = (thisChannel?.io)!
}
@IBAction func openWriteValuePressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Write Value", message: "What value would you like to write to \(thisChannel!.name)?", preferredStyle: .alert)
let action = UIAlertAction(title: "Write", style: .default) { (action) in
// what will happen once the user clicks the add item button on our UIAlert
SVProgressHUD.show()
firstly {
writeChannelValue(deviceId: (self.thisDevice?.id)!, channelName: (self.thisChannel?.name)!, value: textField.text!, baseURL: self.baseURL, authToken: (self.user?.authToken)!)
}.then{ _ in
getChannelHistory(deviceId: (self.thisDevice?.id)!, channelId: (self.thisChannel?.id)!, baseURL: self.baseURL, authToken: (self.user?.authToken)!)
}.done { (hist) in
self.channelHistory = hist
self.historyTableView.reloadData()
SVProgressHUD.dismiss()
}.catch { error in
print("ERROR IN openWriteValue: \(error)")
}
}
alert.addTextField { (valueTextField) in
valueTextField.placeholder = "123.4567"
textField = valueTextField
}
alert.addAction(action)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
func getFirebaseChannelHistory(deviceMacAddress: String, deviceTypeName : String, channelName : String) -> Promise<[ChannelHistoryValue]>{
return Promise { promise in
var channelHist : [ChannelHistoryValue] = [ChannelHistoryValue]()
let getVals = self.ref.child("devices")
.child(deviceMacAddress)
.child(deviceTypeName)
.child("history")
.child(channelName)
.observe(.value) { snapshot in
if let snapValue = snapshot.value as? NSDictionary {
for (_, value) in snapValue {
let valueJSON : JSON = JSON(value)
let chVal = ChannelHistoryValue()
chVal.value = valueJSON["value"].stringValue
chVal.timestamp = Date(timeIntervalSince1970: Double(valueJSON["timestamp"].intValue))
channelHist.append(chVal)
}
promise.fulfill(channelHist.sorted(by: { (firstVal, secondVal) -> Bool in
return firstVal.timestamp! > secondVal.timestamp!
}))
} else {
print("ref: \(snapshot.ref)")
promise.reject("Bad NSDictionary in getFirebaseChannelHistory" as! Error)
}
}
ref.removeObserver(withHandle: getVals)
}
}
}