FacilitiesListViewController.swift 18.9 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
	let realm = try! Realm()

Zach Knox's avatar
Zach Knox committed
25
	var facilitiesArray = List<Facility>()
26
27
    
    // array of facilities that pass the current filters
Zac Wood's avatar
Zac Wood committed
28
    var filteredFacilities = List<Facility>()
29
30
31
	
	// List which actually pertains to what is shown
	var shownFacilities = List<Facility>()
Zac Wood's avatar
Zac Wood committed
32
    
33
    // passing in nil sets the search controller to be this controller
Zac Wood's avatar
Zac Wood committed
34
35
    let searchController = UISearchController(searchResultsController: nil)

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

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

52
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
Zach Knox's avatar
Zach Knox committed
53

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

57
	@IBOutlet var LastUpdatedLabel: UIBarButtonItem!
58
59
    
    let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
60

Zach Knox's avatar
Zach Knox committed
61
	@IBAction func favoritesControlChanges(_ sender: Any) {
62
		switch self.favoritesControl.selectedSegmentIndex
Zach Knox's avatar
Zach Knox committed
63
64
65
		{
		case 0:
			showFavorites = false
66
			shownFacilities = filteredFacilities
Zach Knox's avatar
Zach Knox committed
67
		case 1:
68
            showFavorites = true
69
			shownFacilities = filterFacilitiesForFavorites()
Zach Knox's avatar
Zach Knox committed
70
71
		default:
			showFavorites = false
72
			shownFacilities = filteredFacilities
Zach Knox's avatar
Zach Knox committed
73
74
75
		}
		self.LocationsList.reloadData()
	}
76
77
78
79
80
81
82
83
84
85
86
    
    /**
     Get all of the facilities that are favorited.
     
     - returns:
        List of facilities that are favorited
     */
    func filterFacilitiesForFavorites() -> List<Facility> {
        var favoriteFacilites = List<Facility>()
        
        // add the facility to favorites list if it is a favorite
87
        favoriteFacilites = filteredFacilities.filter({ (facility: Facility) -> Bool in
88
89
90
91
92
            return Utilities.isFavoriteFacility(facility)
        })
        
        return favoriteFacilites
    }
Zach Knox's avatar
Zach Knox committed
93

94
	override func viewWillLayoutSubviews() {
Zach Knox's avatar
Zach Knox committed
95
96
97
98
99
		LocationsListLayout.itemSize.width = getCellWidth()
		LocationsListLayout.invalidateLayout()
	}
	
	func getCellWidth() -> CGFloat {
100
101
		let windowWidth = self.view.frame.size.width
		
Zach Knox's avatar
Zach Knox committed
102
103
		if(windowWidth < 640) {
			return windowWidth - 20
104
105
		}
		else if(windowWidth >= 640 && windowWidth < 1024) {
Zach Knox's avatar
Zach Knox committed
106
			return (windowWidth / 2) - 15
107
108
		}
		else if(windowWidth >= 1024) {
Zach Knox's avatar
Zach Knox committed
109
			return (windowWidth / 3) - 15
110
111
		}
		
Zach Knox's avatar
Zach Knox committed
112
		return 0
113
	}
Zach Knox's avatar
Zach Knox committed
114

115
	@IBAction func RefreshButton(_ sender: Any) {
Zach Knox's avatar
Zach Knox committed
116
		refresh(sender, forceUpdate: true)
117
	}
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
	
	func checkFilterState() {
		if(filters.showOpen && filters.showClosed && filters.openFirst && filters.sortBy == SortMethod.alphabetical) {
			for f in filters.onlyFromCategories {
				if(f.value != true) {
					LeftButton.title = "Filter (On)"
					return
				}
			}
			for f in filters.onlyFromLocations {
				if(f.value != true) {
					LeftButton.title = "Filter (On)"
					return
				}
			}
			LeftButton.title = "Filter"
			return
		}
		LeftButton.title = "Filter (On)"
	}
Zach Knox's avatar
Zach Knox committed
138

139
140
	override func viewWillAppear(_ animated: Bool) {
		LastUpdatedLabel.isEnabled = false
141
		checkFilterState()
142
		reloadWithFilters()
143
144
	}
	
Zach Knox's avatar
Zach Knox committed
145
	@objc func tapRecognizer(_ sender: UITapGestureRecognizer) {
Zach Knox's avatar
Zach Knox committed
146
147
148
		
		let tapLocation = sender.location(in: LocationsList)
		let indexPath = LocationsList.indexPathForItem(at: tapLocation)
Zac Wood's avatar
Zac Wood committed
149
        
Zach Knox's avatar
Zach Knox committed
150
		if((indexPath) != nil) {
Zac Wood's avatar
Zac Wood committed
151
152
153
154
            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
155
156
157
158
159
160
161
		}
	}
	
	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
162
163
164
165
			destination.modalPresentationStyle = .popover
			let popoverController = destination.popoverPresentationController
			popoverController?.permittedArrowDirections = .any
			popoverController?.sourceView = destination.view
Zac Wood's avatar
Zac Wood committed
166
167
168
169
170
171
172
173
            
            // 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
174
175
176
177
178
		}
		else {
			let destDelegate = DeckTransitioningDelegate()
			destination.modalPresentationStyle = .custom
			destination.transitioningDelegate = destDelegate
Zac Wood's avatar
Zac Wood committed
179
180
181
182
183
184
185
186
            
            // 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
187
		}
Zac Wood's avatar
Zac Wood committed
188
189
        
        
Zach Knox's avatar
Zach Knox committed
190
	}
Zac Wood's avatar
Zac Wood committed
191
192
193
194
195
196
197
198
199
    
    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
200
201
	
	override func viewDidLoad() {
202
203
        super.viewDidLoad()
		
204
205
		self.definesPresentationContext = true
		
Zach Knox's avatar
Zach Knox committed
206
		if(traitCollection.forceTouchCapability == .available) {
207
208
			registerForPreviewing(with: self, sourceView: self.LocationsList!)
		}
Zach Knox's avatar
Zach Knox committed
209
210
        
        navigationItem.title = "What's Open"
211
		navigationController?.navigationBar.prefersLargeTitles = true
212
213
		navigationItem.largeTitleDisplayMode = .always
		
Zac Wood's avatar
Zac Wood committed
214
        configureSearchController()
Zach Knox's avatar
Zach Knox committed
215
		
216
		LocationsListLayout.invalidateLayout()
Zach Knox's avatar
Zach Knox committed
217
		
218
219
220
		settingsButton.accessibilityLabel = "Settings"
		LastUpdatedLabel.accessibilityHint = ""
		
221
		LocationsListLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
Zach Knox's avatar
Zach Knox committed
222

Zach Knox's avatar
Zach Knox committed
223
		refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
224
		LocationsList.refreshControl = refreshControl
Zach Knox's avatar
Zach Knox committed
225
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
226

Zach Knox's avatar
Zach Knox committed
227
		
Zach Knox's avatar
Zach Knox committed
228
		/*
Zach Knox's avatar
Zach Knox committed
229
230
231
232
233
		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)
234
		}
Zach Knox's avatar
Zach Knox committed
235
236
237
238
239
		else if(lastUpdatedList! < Date(timeIntervalSinceNow: -86400.0)) {
			refresh(self)
		}
		else {
			facilitiesArray = facilitiesFromDefaults!
240
		}
Zach Knox's avatar
Zach Knox committed
241
		*/
242
		
Zach Knox's avatar
Zach Knox committed
243
		refresh(self, forceUpdate: false)
Zach Knox's avatar
Zach Knox committed
244
		
245

Zach Knox's avatar
Zach Knox committed
246
		
247
		reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
248
249
		
		
250
	}
Zach Knox's avatar
Zach Knox committed
251
	
252
253
254
255
256
257
	func reloadWithFilters() {
		filteredFacilities = filters.applyFiltersOnFacilities(facilitiesArray)
		shownFacilities = filteredFacilities
		favoritesControlChanges(self)
		LocationsList.reloadData()
	}
Zac Wood's avatar
Zac Wood committed
258
259
260
261
262
263
264
265
266
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
267
268
269
270
271
272
273
274
275
276
    /**
     Filters facilities based on the text inputted into the search controller.
     
     - parameters:
        - searchText: text used to filter the facilities.
     - returns:
        List of filtered facilities. Facilities whose names, buildings, or categories match the search text are included.
     */
    func filterFacilitiesForSearchText(_ searchText: String) -> List<Facility> {
        var filtered: List<Facility>
277
278
		
		/*
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        if showFavorites {
            let favoriteFacilities = filterFacilitiesForFavorites()
            
            if searchText == "" { // if the search text is empty, just return the favorites.
                filtered = favoriteFacilities
            } else {
                filtered = favoriteFacilities.filter({(facility: Facility) -> Bool in
                    let hasName = facility.facilityName.lowercased().contains(searchText.lowercased())
                    let hasBuilding = facility.facilityLocation?.building.lowercased().contains(searchText.lowercased()) ?? false
                    let hasCategory = facility.category?.categoryName.lowercased().contains(searchText.lowercased()) ?? false
                    
                    return hasName || hasBuilding || hasCategory
                })
            }
293

294
        } else {
295
296
297
298
299
300
301
302
303
304
305
306
307
		  */
		if searchText == "" {
			filtered = shownFacilities
			LocationsList.reloadData()
			return shownFacilities
		}
		filtered = filteredFacilities.filter({(facility: Facility) -> Bool in
			let hasName = facility.facilityName.lowercased().contains(searchText.lowercased())
			let hasBuilding = facility.facilityLocation?.building.lowercased().contains(searchText.lowercased()) ?? false
			let hasCategory = facility.category?.categoryName.lowercased().contains(searchText.lowercased()) ?? false
			
			return hasName || hasBuilding || hasCategory
		})
308
        
Zac Wood's avatar
Zac Wood committed
309
        LocationsList.reloadData()
310
        return filtered
Zac Wood's avatar
Zac Wood committed
311
    }
Zach Knox's avatar
Zach Knox committed
312
	
313
314
315
316
	/*
	* Reloads data, either calling update() to attempt a download
	* or simply pulling from the realm
	*/
Zach Knox's avatar
Zach Knox committed
317
	func refresh(_ sender: Any, forceUpdate: Bool = true) {
Zach Knox's avatar
Zach Knox committed
318
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
		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
Zach Knox's avatar
Zach Knox committed
334
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
Zach Knox's avatar
Zach Knox committed
335
336
337
338
339
340
341
				}
			}
			else {
				update(sender)
			}

		}
342
		reloadWithFilters()
343
344
345
346
347
348
349
350
351
352
		
		// Add locations and categories to filters
		for f in facilitiesArray {
			if(!filters.onlyFromCategories.keys.contains((f.category?.categoryName)!)) {
				filters.onlyFromCategories.updateValue(true, forKey: (f.category?.categoryName)!)
			}
			if(!filters.onlyFromLocations.keys.contains((f.facilityLocation?.building)!)) {
				filters.onlyFromLocations.updateValue(true, forKey: (f.facilityLocation?.building)!)
			}
		}
Zach Knox's avatar
Zach Knox committed
353
354
		refreshControl.endRefreshing()
	}
Zach Knox's avatar
Zach Knox committed
355
	
356
357
358
359
	/*
	* Attempts to update facilitiesArray from the network
	* and place that new information into Realm
	*/
Zach Knox's avatar
Zach Knox committed
360
	func update(_ sender: Any) {
361
		SRCTNetworkController.performDownload { (facilities) in
Zach Knox's avatar
Zach Knox committed
362
363
364
365
366
367
368
369
370
			if(facilities == nil) {
				DispatchQueue.main.async {
					let results = self.realm.objects(FacilitiesModel.self)
					if results.count > 0 {
						let model = results[0]
						let facilitiesFromDB = model.facilities
						let lastUpdated = model.lastUpdated
						
						self.facilitiesArray = facilitiesFromDB
371
						self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
372
373
374
375
						self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
					}
					else {
						self.facilitiesArray = List<Facility>()
Zach Knox's avatar
Zach Knox committed
376
377
					}
				}
Zach Knox's avatar
Zach Knox committed
378
379
380
381
382
383
384
385
386
			}
			else {
				self.facilitiesArray = facilities!
				
				DispatchQueue.main.async {
					//let defaults = UserDefaults.standard
					//defaults.set(facilities, forKey: "FacilitiesList")
					let date = Date()
					//defaults.set(date, forKey: "lastUpdatedList")
387
					self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(date)
					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
404
405
					}
				}
Zach Knox's avatar
Zach Knox committed
406
			}
Zach Knox's avatar
Zach Knox committed
407
			
Zach Knox's avatar
Zach Knox committed
408
409

			
410
		}
Zach Knox's avatar
Zach Knox committed
411
	}
Zac Wood's avatar
Zac Wood committed
412
    
413
414
415
416
417
418
419
420
421
	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
422
	
423
424
425
426
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
Zach Knox's avatar
Zach Knox committed
427

428
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
429
		return 1
430
	}
Zach Knox's avatar
Zach Knox committed
431

432
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
433
        return shownFacilities.count
434
	}
Zach Knox's avatar
Zach Knox committed
435

436
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
437
		let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! FacilityCollectionViewCell
Zach Knox's avatar
Zach Knox committed
438
439
440
441
442
443
444
		/*
		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
445
        //Get tap of the cell
446
		cell.tapRecognizer.addTarget(self, action: #selector(FacilitiesListViewController.tapRecognizer(_:)))
Zach Knox's avatar
Zach Knox committed
447
        cell.gestureRecognizers = []
448
		cell.gestureRecognizers?.append(cell.tapRecognizer)
Zach Knox's avatar
Zach Knox committed
449
        
Zac Wood's avatar
Zac Wood committed
450
451
        
        let facility: Facility
452
453
454
        //let dataArray: [Facility]
		
		/*
Zac Wood's avatar
Zac Wood committed
455
        // if something has been searched for, we want to use the filtered array as the data source
Zach Knox's avatar
Zach Knox committed
456
        if isSearching() || showFavorites {
Zac Wood's avatar
Zac Wood committed
457
458
459
460
            dataArray = placeOpenFacilitiesFirstInArray(filteredFacilities)
        } else {
            dataArray = placeOpenFacilitiesFirstInArray(facilitiesArray)
        }
461
462
463
		*/
		
		
Zac Wood's avatar
Zac Wood committed
464
        
465
		facility = shownFacilities[indexPath.row]
Zac Wood's avatar
Zac Wood committed
466
        
467
		cell.facility = facility
Zach Knox's avatar
Zach Knox committed
468
469
        
        //set labels
Zach Knox's avatar
Zach Knox committed
470
		cell.nameLabel.text = facility.facilityName
471
        cell.categoryLabel.text = facility.category?.categoryName.uppercased()
Zach Knox's avatar
Zach Knox committed
472

Zach Knox's avatar
Zach Knox committed
473
474
475
476
477
478
        cell.openClosedLabel.text = Utilities.openOrClosedUntil(facility)
        
        cell.timeDescriptionLabel.text = facility.facilityLocation?.building

        //change appearence based on open state
        let open = Utilities.isOpen(facility: facility)
479
		if(open == true) {
480
			//cell.openClosedLabel.text = "Open"
481
482
483
			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)
484
			cell.backgroundColor = UIColor(red:0.00, green:0.40, blue:0.20, alpha:1.0)
485
		} else {
486
			//cell.openClosedLabel.text = "Closed"
487
488
489
			cell.openClosedLabel.textColor = UIColor.white
			cell.openClosedLabel.backgroundColor = UIColor.black
			//cell.openClosedLabel.backgroundColor = UIColor.red
490
491
			cell.backgroundColor = UIColor.red

492
		}
Zach Knox's avatar
Zach Knox committed
493

Zach Knox's avatar
Zach Knox committed
494
        //Accessibility
495
        //TODO: FIX THIS
496
497
498
499
		cell.accessibilityLabel = cell.nameLabel.text! + ", Currently " + cell.openClosedLabel.text! + "." + cell.timeDescriptionLabel.text!
		cell.accessibilityHint = "Double Tap to view details"

		
500
501
502
		self.reloadInputViews()
		return cell
	}
Zach Knox's avatar
Zach Knox committed
503

504
505
	
	//unused
Zach Knox's avatar
Zach Knox committed
506
	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
507
508
509
510
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
511
			return placeOpenFacilitiesFirstInArray(filteredFacilities)
Zach Knox's avatar
Zach Knox committed
512
		}
Zach Knox's avatar
Zach Knox committed
513
514


Zach Knox's avatar
Zach Knox committed
515
	}
516
	
517
	//unused
Zac Wood's avatar
Zac Wood committed
518
519
520
	// 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
521
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
522
523
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
524

525
526
527
528
529
530
531
532
533
534
535
		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
536

537
	//unused
538
539
540
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
541

542
543
544
545
546
547
548
549
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
550

551
552
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
553
554


555
556
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
557
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zach Knox's avatar
Zach Knox committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
    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.facilities = self.facilitiesArray
            filterView.filters = self.filters
        }

        // Pass the selected object to the new view controller.
    }
583
	
584
585
586
587
	// MARK: - Peek and Pop
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
		guard let indexPath = LocationsList?.indexPathForItem(at: location) else { return nil }
588
589
		let cell = LocationsList?.cellForItem(at: indexPath) as! FacilityCollectionViewCell
		guard let detailView = storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController else { return nil }
590
591
		
		detailView.facility = cell.facility
Zach Knox's avatar
Zach Knox committed
592

593
594
595
596
		return detailView
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
Zach Knox's avatar
Zach Knox committed
597
598
599
600
601
		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)
602
603
	}
	
604
}
Zac Wood's avatar
Zac Wood committed
605
606
607
608
609

// 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 ?? ""
610
        filteredFacilities = filterFacilitiesForSearchText(searchText)
Zac Wood's avatar
Zac Wood committed
611
612
613
    }
}

Zach Knox's avatar
Zach Knox committed
614
615