FacilitiesListViewController.swift 14.8 KB
Newer Older
1
2
3
4
5
//
//  LocationsListViewController.swift
//  WhatsOpen
//
//  Created by Zach Knox on 4/5/17.
Zach Knox's avatar
Zach Knox committed
6
//  Copyright © 2017 SRCT. Some rights reserved.
7
8
9
//

import UIKit
Zach Knox's avatar
Zach Knox committed
10
import DeckTransition
Zach Knox's avatar
Zach Knox committed
11
import RealmSwift
12

Zach Knox's avatar
Zach Knox committed
13
14
15
16
17
18
19
20
//Realm Model
class FacilitiesModel: Object {
	var facilities = List<Facility>()
	@objc dynamic var lastUpdated = Date()
	@objc dynamic let id = 0
}


21
class FacilitiesListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIViewControllerPreviewingDelegate {
22

Zach Knox's avatar
Zach Knox committed
23
24
25
26
27
	let realm = try! Realm()

	
	
	
Zach Knox's avatar
Zach Knox committed
28
	var facilitiesArray = List<Facility>()
Zac Wood's avatar
Zac Wood committed
29
30
31
32
33
    var filteredFacilities = List<Facility>()
    
    // passing in nil sets the controller to be this controller
    let searchController = UISearchController(searchResultsController: nil)

Zach Knox's avatar
Zach Knox committed
34
	var filters = Filters()
35
	
36
37
38
39
	override var preferredStatusBarStyle: UIStatusBarStyle {
		return .default
	}
	
40
	@IBOutlet var LeftButton: UIBarButtonItem!
Zach Knox's avatar
Zach Knox committed
41

42
43
44
45
	@IBAction func RightButton(_ sender: Any) {
	}
	@IBOutlet var RightButton: UIBarButtonItem!
	
46
47
	@IBOutlet var settingsButton: UIBarButtonItem!
	
48
	@IBOutlet var LocationsList: UICollectionView!
Zach Knox's avatar
Zach Knox committed
49

50
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
Zach Knox's avatar
Zach Knox committed
51

52
	@IBOutlet var favoritesControl: UISegmentedControl!
Zach Knox's avatar
Zach Knox committed
53
54
	var showFavorites = false

55
	@IBOutlet var LastUpdatedLabel: UIBarButtonItem!
Zach Knox's avatar
Zach Knox committed
56

Zach Knox's avatar
Zach Knox committed
57
58
59
60
61
62
63
64
65
66
67
68
	@IBAction func favoritesControlChanges(_ sender: Any) {
		switch (self.favoritesControl.selectedSegmentIndex)
		{
		case 0:
			showFavorites = false
		case 1:
			showFavorites = true
		default:
			showFavorites = false
		}
		self.LocationsList.reloadData()
	}
Zach Knox's avatar
Zach Knox committed
69

Zach Knox's avatar
Zach Knox committed
70
	let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
71

72
	override func viewWillLayoutSubviews() {
Zach Knox's avatar
Zach Knox committed
73
74
75
76
77
78
		LocationsListLayout.itemSize.width = getCellWidth()
		LocationsListLayout.invalidateLayout()

	}
	
	func getCellWidth() -> CGFloat {
79
80
		let windowWidth = self.view.frame.size.width
		
Zach Knox's avatar
Zach Knox committed
81
82
		if(windowWidth < 640) {
			return windowWidth - 20
83
84
		}
		else if(windowWidth >= 640 && windowWidth < 1024) {
Zach Knox's avatar
Zach Knox committed
85
			return (windowWidth / 2) - 15
86
87
		}
		else if(windowWidth >= 1024) {
Zach Knox's avatar
Zach Knox committed
88
			return (windowWidth / 3) - 15
89
90
		}
		
Zach Knox's avatar
Zach Knox committed
91
		return 0
92
	}
Zach Knox's avatar
Zach Knox committed
93

94
	@IBAction func RefreshButton(_ sender: Any) {
Zach Knox's avatar
Zach Knox committed
95
		refresh(sender, forceUpdate: true)
96
	}
Zach Knox's avatar
Zach Knox committed
97

98
99
100
101
	override func viewWillAppear(_ animated: Bool) {
		LastUpdatedLabel.isEnabled = false
	}
	
Zach Knox's avatar
Zach Knox committed
102
	@objc func tapRecognizer(_ sender: UITapGestureRecognizer) {
Zach Knox's avatar
Zach Knox committed
103
104
105
		
		let tapLocation = sender.location(in: LocationsList)
		let indexPath = LocationsList.indexPathForItem(at: tapLocation)
Zac Wood's avatar
Zac Wood committed
106
        
Zach Knox's avatar
Zach Knox committed
107
		if((indexPath) != nil) {
Zac Wood's avatar
Zac Wood committed
108
109
110
111
112
            let destination = self.storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController
            let tapped = self.LocationsList.cellForItem(at: indexPath!) as! FacilityCollectionViewCell
            destination!.facility = tapped.facility
            self.presentDetailView(destination!)
            
Zach Knox's avatar
Zach Knox committed
113
114
115
116
117
118
119
		}
	}
	
	func presentDetailView(_ destination: FacilityDetailViewController) {
		if(self.view.traitCollection.horizontalSizeClass == .regular && self.view.traitCollection.verticalSizeClass == .regular) {
			//do a popover here for the iPad
			//iPads are cool right?
Zach Knox's avatar
Zach Knox committed
120
121
122
123
			destination.modalPresentationStyle = .popover
			let popoverController = destination.popoverPresentationController
			popoverController?.permittedArrowDirections = .any
			popoverController?.sourceView = destination.view
Zac Wood's avatar
Zac Wood committed
124
125
126
127
128
129
130
131
            
            // present the detail view over the search controller if we're searching
            if searchController.isActive {
                searchController.present(destination, animated: true, completion: nil)
            }
            else {
                present(destination, animated: true, completion: nil)
            }
Zach Knox's avatar
Zach Knox committed
132
133
134
135
136
		}
		else {
			let destDelegate = DeckTransitioningDelegate()
			destination.modalPresentationStyle = .custom
			destination.transitioningDelegate = destDelegate
Zac Wood's avatar
Zac Wood committed
137
138
139
140
141
142
143
144
            
            // present the detail view over the search controller if we're searching
            if searchController.isActive {
                searchController.present(destination, animated: true, completion: nil)
            }
            else {
                present(destination, animated: true, completion: nil)
            }
Zach Knox's avatar
Zach Knox committed
145
		}
Zac Wood's avatar
Zac Wood committed
146
147
        
        
Zach Knox's avatar
Zach Knox committed
148
	}
Zac Wood's avatar
Zac Wood committed
149
150
151
152
153
154
155
156
157
    
    func configureSearchController() {
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        
        // add it to the navigationItem
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = true
    }
Zach Knox's avatar
Zach Knox committed
158
159
	
	override func viewDidLoad() {
160
161
        super.viewDidLoad()
		
162
163
		self.definesPresentationContext = true
		
Zach Knox's avatar
Zach Knox committed
164
		if(traitCollection.forceTouchCapability == .available) {
165
166
			registerForPreviewing(with: self, sourceView: self.LocationsList!)
		}
Zach Knox's avatar
Zach Knox committed
167
168
        
        navigationItem.title = "What's Open"
169
		navigationController?.navigationBar.prefersLargeTitles = true
170
171
		navigationItem.largeTitleDisplayMode = .always
		
Zac Wood's avatar
Zac Wood committed
172
        configureSearchController()
Zach Knox's avatar
Zach Knox committed
173
		
174
		LocationsListLayout.invalidateLayout()
Zach Knox's avatar
Zach Knox committed
175
		
176
177
178
		settingsButton.accessibilityLabel = "Settings"
		LastUpdatedLabel.accessibilityHint = ""
		
179
		LocationsListLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
Zach Knox's avatar
Zach Knox committed
180

Zach Knox's avatar
Zach Knox committed
181
		refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
182
		LocationsList.refreshControl = refreshControl
Zach Knox's avatar
Zach Knox committed
183
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
184

Zach Knox's avatar
Zach Knox committed
185
		
Zach Knox's avatar
Zach Knox committed
186
		/*
Zach Knox's avatar
Zach Knox committed
187
188
189
190
191
192
193
194
195
196
197
		let defaults = UserDefaults.standard
		let facilitiesFromDefaults = defaults.object(forKey: "FacilitiesList") as! List<Facility>?
	  	let lastUpdatedList = defaults.object(forKey: "lastUpdatedList") as! Date?
		if(facilitiesFromDefaults == nil || lastUpdatedList == nil) {
			refresh(self)
		}
		else if(lastUpdatedList! < Date(timeIntervalSinceNow: -86400.0)) {
			refresh(self)
		}
		else {
			facilitiesArray = facilitiesFromDefaults!
198
		}
Zach Knox's avatar
Zach Knox committed
199
200
201
		*/
		
		refresh(self, forceUpdate: false)
202
		LocationsList.reloadData()
203
	}
Zach Knox's avatar
Zach Knox committed
204
205
	
	
Zac Wood's avatar
Zac Wood committed
206
207
208
209
210
211
212
213
214
215
216
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
    func filterFacilitiesForSearchText(_ searchText: String) {
        filteredFacilities = facilitiesArray.filter({(facility: Facility) -> Bool in
Zac Wood's avatar
Zac Wood committed
217
218
            let hasName = facility.facilityName.lowercased().contains(searchText.lowercased())
            let hasBuilding = facility.facilityLocation?.building.lowercased().contains(searchText.lowercased()) ?? false
219
220
			let hasCategory = facility.category?.categoryName.lowercased().contains(searchText.lowercased()) ?? false
            return hasName || hasBuilding || hasCategory
Zac Wood's avatar
Zac Wood committed
221
222
223
        })
        LocationsList.reloadData()
    }
Zach Knox's avatar
Zach Knox committed
224
	
Zach Knox's avatar
Zach Knox committed
225
	func refresh(_ sender: Any, forceUpdate: Bool = true) {
Zach Knox's avatar
Zach Knox committed
226
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
		if(forceUpdate) {
			update(sender);
		}
		else {
			let results = realm.objects(FacilitiesModel.self)
			if results.count > 0 {
				let model = results[0]
				let facilities = model.facilities
				let lastUpdated = model.lastUpdated
				
				if(facilities.isEmpty || lastUpdated < Date(timeIntervalSinceNow: -86400.0)) {
					update(sender)
				}
				else {
					facilitiesArray = facilities
				}
			}
			else {
				update(sender)
			}

		}
		LocationsList.reloadData()
		refreshControl.endRefreshing()
	}
	
	func update(_ sender: Any) {
254
255
256
257
		SRCTNetworkController.performDownload { (facilities) in
			self.facilitiesArray = facilities
			
			DispatchQueue.main.async {
Zach Knox's avatar
Zach Knox committed
258
				//let defaults = UserDefaults.standard
259
				//defaults.set(facilities, forKey: "FacilitiesList")
Zach Knox's avatar
Zach Knox committed
260
				let date = Date()
Zach Knox's avatar
Zach Knox committed
261
				//defaults.set(date, forKey: "lastUpdatedList")
262
				self.LocationsList.reloadData()
Zach Knox's avatar
Zach Knox committed
263
				self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(date)
Zach Knox's avatar
Zach Knox committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
				let model = FacilitiesModel()
				model.facilities = facilities
				model.lastUpdated = date
				let results = self.realm.objects(FacilitiesModel.self)
				if results.count == 0 {
					try! self.realm.write {
						self.realm.add(model)
					}
				}
				else {
					let fromRealm = results[0]
					try! self.realm.write {
						fromRealm.facilities = model.facilities
						fromRealm.lastUpdated = model.lastUpdated
					}
				}
Zach Knox's avatar
Zach Knox committed
280
			}
Zach Knox's avatar
Zach Knox committed
281
			
282
		}
Zach Knox's avatar
Zach Knox committed
283
	}
Zac Wood's avatar
Zac Wood committed
284
    
285
286
287
288
289
290
291
292
293
	func shortDateFormat(_ date: Date) -> String {
		let dateFormatter = DateFormatter()
		dateFormatter.dateStyle = .short
		dateFormatter.timeStyle = .short

		// US English Locale (en_US)
		dateFormatter.locale = Locale(identifier: "en_US")
		return dateFormatter.string(from: date)
	}
Zach Knox's avatar
Zach Knox committed
294
	
295
296
297
298
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
Zach Knox's avatar
Zach Knox committed
299

300
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
301
		return 1
302
	}
Zach Knox's avatar
Zach Knox committed
303

304
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
Zac Wood's avatar
Zac Wood committed
305
        return isSearching() ? self.filteredFacilities.count : self.facilitiesArray.count
306
	}
Zach Knox's avatar
Zach Knox committed
307

308
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
309
		let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! FacilityCollectionViewCell
Zach Knox's avatar
Zach Knox committed
310
311
312
313
314
315
316
		/*
		let windowRect = self.view.window!.frame
		let windowWidth = windowRect.size.width
		if(windowWidth <= 320) {
			cell.frame.size.width = 280
		}
		*/
Zach Knox's avatar
Zach Knox committed
317
        //Get tap of the cell
318
		cell.tapRecognizer.addTarget(self, action: #selector(FacilitiesListViewController.tapRecognizer(_:)))
Zach Knox's avatar
Zach Knox committed
319
        cell.gestureRecognizers = []
320
		cell.gestureRecognizers?.append(cell.tapRecognizer)
Zach Knox's avatar
Zach Knox committed
321
        
Zac Wood's avatar
Zac Wood committed
322
323
324
325
326
327
328
329
330
331
332
333
334
        
        let facility: Facility
        let dataArray: [Facility]
        
        // if something has been searched for, we want to use the filtered array as the data source
        if isSearching() {
            dataArray = placeOpenFacilitiesFirstInArray(filteredFacilities)
        } else {
            dataArray = placeOpenFacilitiesFirstInArray(facilitiesArray)
        }
        
		facility = dataArray[indexPath.row]
        
335
		cell.facility = facility
Zach Knox's avatar
Zach Knox committed
336
337
        
        //set labels
Zach Knox's avatar
Zach Knox committed
338
		cell.nameLabel.text = facility.facilityName
339
        cell.categoryLabel.text = facility.category?.categoryName.uppercased()
Zach Knox's avatar
Zach Knox committed
340

Zach Knox's avatar
Zach Knox committed
341
342
343
344
345
346
        cell.openClosedLabel.text = Utilities.openOrClosedUntil(facility)
        
        cell.timeDescriptionLabel.text = facility.facilityLocation?.building

        //change appearence based on open state
        let open = Utilities.isOpen(facility: facility)
347
		if(open == true) {
348
			//cell.openClosedLabel.text = "Open"
349
350
351
			cell.openClosedLabel.textColor = UIColor.black
			cell.openClosedLabel.backgroundColor = UIColor.white
			//cell.openClosedLabel.backgroundColor = UIColor(red:0.00, green:0.40, blue:0.20, alpha:1.0)
352
			cell.backgroundColor = UIColor(red:0.00, green:0.40, blue:0.20, alpha:1.0)
353
		} else {
354
			//cell.openClosedLabel.text = "Closed"
355
356
357
			cell.openClosedLabel.textColor = UIColor.white
			cell.openClosedLabel.backgroundColor = UIColor.black
			//cell.openClosedLabel.backgroundColor = UIColor.red
358
359
			cell.backgroundColor = UIColor.red

360
		}
Zach Knox's avatar
Zach Knox committed
361

Zach Knox's avatar
Zach Knox committed
362
        //Accessibility
363
        //TODO: FIX THIS
364
365
366
367
		cell.accessibilityLabel = cell.nameLabel.text! + ", Currently " + cell.openClosedLabel.text! + "." + cell.timeDescriptionLabel.text!
		cell.accessibilityHint = "Double Tap to view details"

		
368
369
370
		self.reloadInputViews()
		return cell
	}
Zach Knox's avatar
Zach Knox committed
371
372

	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
373
374
375
376
377
378
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
			return [] //TODO - INCOMPLETE
		}
Zach Knox's avatar
Zach Knox committed
379
380


Zach Knox's avatar
Zach Knox committed
381
	}
Zach Knox's avatar
Zach Knox committed
382

Zac Wood's avatar
Zac Wood committed
383
384
385
	// Returns an array which has the open locations listed first
	// Could be improved in the future because currently this means you're checking
	// open status twice per cell
Zach Knox's avatar
Zach Knox committed
386
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
387
388
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
389

390
391
392
393
394
395
396
397
398
399
400
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open.append(i)
			}
			else {
				closed.append(i)
			}
		}
		// Test
		return open + closed
	}
Zach Knox's avatar
Zach Knox committed
401

402
403
404
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
405

406
407
408
409
410
411
412
413
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
414

415
416
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
417
418


419
420
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
421
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zac Wood's avatar
Zac Wood committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        // Get the new view controller using segue.destinationViewController.
//        if(segue.identifier == "toDetailView") {
//            let destination = segue.destination as! FacilityDetailViewController
//            let destDelegate = DeckTransitioningDelegate()
//            destination.transitioningDelegate = destDelegate
//            let tapped = sender as! FacilityCollectionViewCell //this is probably a bad idea just FYI future me
//            destination.facility = tapped.facility
//
//            // if we're in the search view, present on its controller
//            if searchController.isActive {
//                searchController.present(destination, animated: true, completion: nil)
//            } else {
//                present(destination, animated: true, completion: nil)
//            }
//        }
//        else if(segue.identifier == "toFilters") {
//            let destination = segue.destination as! UINavigationController
//            let filterView = destination.topViewController as! FiltersTableViewController
//            filterView.filters = self.filters
//        }
//
//        // Pass the selected object to the new view controller.
//    }
446
	
447
448
449
450
	// MARK: - Peek and Pop
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
		guard let indexPath = LocationsList?.indexPathForItem(at: location) else { return nil }
451
452
		let cell = LocationsList?.cellForItem(at: indexPath) as! FacilityCollectionViewCell
		guard let detailView = storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController else { return nil }
453
454
		
		detailView.facility = cell.facility
Zach Knox's avatar
Zach Knox committed
455

456
457
458
459
		return detailView
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
Zach Knox's avatar
Zach Knox committed
460
461
462
463
464
		let destDelegate = DeckTransitioningDelegate()
		viewControllerToCommit.modalPresentationStyle = .custom
		viewControllerToCommit.transitioningDelegate = destDelegate
		//If one day 3D touch comes to the iPad, this is no longer good.
		present(viewControllerToCommit, animated: true, completion: nil)
465
466
	}
	
467
}
Zac Wood's avatar
Zac Wood committed
468
469
470
471
472
473
474
475
476

// by implementing UISearchResultsUpdating, we can use this controller for the search controller
extension FacilitiesListViewController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        let searchText = searchController.searchBar.text ?? ""
        filterFacilitiesForSearchText(searchText)
    }
}

Zach Knox's avatar
Zach Knox committed
477
478