jsoncreator_app/JSONCreator_iOS/JSONCreator/MasterViewController.swift
2020-01-28 11:54:24 -05:00

228 lines
8.8 KiB
Swift

//
// MasterViewController.swift
// JSONCreator
//
// Created by Scott Pfeil on 8/2/19.
// Copyright © 2019 Verizon Wireless. All rights reserved.
//
import MVMCore
class MasterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//--------------------------------------------------
// MARK: - Outlets
//--------------------------------------------------
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var ipTextField: UITextField!
@IBOutlet weak var requestButton: UIButton!
//--------------------------------------------------
// MARK: - Properties
//--------------------------------------------------
var molecularModels: [MolecularModel] = []
//--------------------------------------------------
// MARK: - Life Cycle
//--------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableView.automaticDimension
ipTextField.text = "127.0.0.1:8181"
requestButton.layer.cornerRadius = 15.0
requestButton.backgroundColor = UIColor.mfGet(forHex: "#d0261d")
guard let ip = ipTextField.text else { return }
let requestParameters = MVMCoreRequestParameters(actionMap: [:])
requestParameters?.parameters = ["category": "Atoms", "filename": "Button"]
requestParameters?.alternateBaseURL = URL(string: "http://\(ip)/v1/fetchAllMolecules")
let errorLocation = (MVMCoreLoadHandler.sharedGlobal()?.errorLocation(forRequest: MVMCoreSessionTimeHandler.sharedSession(), pageType: "", modules: ""))!
MVMCoreDispatchUtility.performBlock(inBackground: {
MVMCoreLoadHandler.sharedGlobal()?.sendRequest(requestParameters!, locationForError: errorLocation, requestFinished: { json, error in
guard error == nil else { return }
do {
try self.fetchAllMolecules(from: json)
MVMCoreDispatchUtility.performSyncBlock(onMainThread: {
self.tableView.reloadData()
})
} catch let myJSONError {
print(myJSONError)
}
})
})
}
func getData(for indexPath: IndexPath) -> String? {
guard let subDictionary = molecularModels[indexPath.section].molecules[indexPath.row] as? [String: Any],
let bb = subDictionary.keys.first,
let val = subDictionary[bb]
else { return nil }
var json: String = ""
do {
let data = try JSONSerialization.data(withJSONObject: val, options: .prettyPrinted)
json = String(data: data, encoding: .utf8)!
} catch {
print(error.localizedDescription)
}
return json
}
//--------------------------------------------------
// MARK: - Table View
//--------------------------------------------------
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return molecularModels[section].category.capitalized
}
func numberOfSections(in tableView: UITableView) -> Int {
return molecularModels.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return molecularModels[section].molecules.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = molecularModels[indexPath.section].molecules[indexPath.row].keys.first as? String ?? "no"
if cell.interactions.first == nil {
let dragInteraction = UIDragInteraction(delegate: self)
cell.addInteraction(dragInteraction)
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIPasteboard.general.string = getData(for: indexPath)
let label = UILabel(frame: .zero)
label.clipsToBounds = true
label.backgroundColor = .gray
label.text = " Copied "
label.font = UIFont.systemFont(ofSize: 30)
label.translatesAutoresizingMaskIntoConstraints = false
label.layer.cornerRadius = 5
view.superview!.addSubview(label)
label.centerXAnchor.constraint(equalTo: view.superview!.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.superview!.centerYAnchor).isActive = true
UIView.animate(withDuration: 2, animations: {
label.alpha = 0
}) { completed in
label.removeFromSuperview()
}
}
//--------------------------------------------------
// MARK: - Methods
//--------------------------------------------------
@IBAction func requestMolecules(_ sender: UIButton) {
guard let ip = ipTextField.text else { return }
let requestParameters = MVMCoreRequestParameters(actionMap: [:])
requestParameters?.parameters = ["category": "Atoms", "filename": "Button"]
requestParameters?.alternateBaseURL = URL(string: "http://\(ip)/v1/fetchAllMolecules")
let errorLocation = (MVMCoreLoadHandler.sharedGlobal()?.errorLocation(forRequest: MVMCoreSessionTimeHandler.sharedSession(), pageType: "", modules: ""))!
MVMCoreDispatchUtility.performBlock(inBackground: {
MVMCoreLoadHandler.sharedGlobal()?.sendRequest(requestParameters!, locationForError: errorLocation, requestFinished: { json, error in
guard error == nil else { return }
do {
try self.fetchAllMolecules(from: json)
MVMCoreDispatchUtility.performSyncBlock(onMainThread: {
self.tableView.reloadData()
})
} catch let myJSONError {
print(myJSONError)
}
})
})
}
func setDetailPage() {
((self.splitViewController?.viewControllers[1] as? UINavigationController)?.topViewController as? DetailViewController)?.textView.text = ""
}
private func fetchAllMolecules(from json: Any?) throws {
let data = try JSONSerialization.data(withJSONObject: json!, options: .prettyPrinted)
let convertedString = String(data: data, encoding: .utf8)?.data(using: .utf8)
guard let dictionary = try JSONSerialization.jsonObject(with: convertedString!, options: []) as? [AnyHashable: Any] else { return }
// Cycle through the categories passed from server.
for (categoryName, content) in dictionary {
let molecularModel = MolecularModel()
molecularModel.category = categoryName as! String
guard let jsonContent = (content as? String)?.data(using: .utf8),
let categoryContent = try JSONSerialization.jsonObject(with: jsonContent, options: []) as? [AnyHashable: Any]
else { continue }
// Cycle through the molecules held by a category.
for (moleculeName, moleculeValue) in categoryContent {
guard let moleculeJSON = (moleculeValue as? String)?.data(using: .utf8),
let moldictionaryCat = try JSONSerialization.jsonObject(with: moleculeJSON, options: []) as? [AnyHashable: Any] else { continue }
molecularModel.molecules.append([moleculeName as! String: moldictionaryCat])
}
molecularModels.append(molecularModel)
}
}
}
// MARK:- Drag Interaction Delegate
extension MasterViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let location = session.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: location),
let content = getData(for: indexPath)
else { return [] }
let provider = NSItemProvider(object: content as NSString)
let item = UIDragItem(itemProvider: provider)
return [item]
}
}