// // 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! @IBOutlet weak var listOptionControl: UISegmentedControl! //-------------------------------------------------- // MARK: - Properties //-------------------------------------------------- var structureModels: [StructureCategoryModel] = [] //-------------------------------------------------- // 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: ""))! DispatchQueue.global(qos: .default).async { MVMCoreLoadHandler.sharedGlobal()?.sendRequest(requestParameters!, locationForError: errorLocation, requestFinished: { json, error in guard error == nil else { return } self.fetchAllMolecules(from: json) DispatchQueue.main.async { self.tableView.reloadData() } }) } } func getData(for indexPath: IndexPath) -> String? { let selectedValue = structureModels[indexPath.section].structures[indexPath.row].value // TODO:... Pretty much all '\t' need an additional \t... switch listOptionControl.selectedSegmentIndex { case 1: return """ { "moleculeName": "listItem", "molecule": \(selectedValue) } """ case 2: return """ { "moleculeName": "stackItem", "molecule": \(selectedValue) } """ default: return selectedValue } } //-------------------------------------------------- // MARK: - Table View //-------------------------------------------------- func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return structureModels[section].category.capitalized } func numberOfSections(in tableView: UITableView) -> Int { return structureModels.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return structureModels[section].structures.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = structureModels[indexPath.section].structures[indexPath.row].key 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 = "\tCopied\t" 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?) { structureModels = [] guard let serverJSON = json, let data = try? JSONSerialization.data(withJSONObject: serverJSON, options: .prettyPrinted), let convertedString = String(data: data, encoding: .utf8)?.data(using: .utf8), let categoryDictionary = try? JSONSerialization.jsonObject(with: convertedString, options: []) as? [AnyHashable: Any] else { return } // Cycle through the categories passed from server. for (categoryName, content) in categoryDictionary { guard let category = categoryName as? String else { continue } let structureCategoryModel = StructureCategoryModel(category: category) guard let data = try? JSONSerialization.data(withJSONObject: content, options: .prettyPrinted), let convertedString = String(data: data, encoding: .utf8)?.data(using: .utf8), let categoryContent = try? JSONSerialization.jsonObject(with: convertedString, options: []) as? [String: String] else { continue } // Cycle through the molecules held by a category. for (structureName, structureValue) in categoryContent { structureCategoryModel.structures.append((key: structureName, value: structureValue)) } structureModels.append(structureCategoryModel) } } } // 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] } }