FacilitiesListViewController.swift 21.6 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
//Realm Model
class FacilitiesModel: Object {
Zach Knox's avatar
Zach Knox committed
15
16
	let facilities = List<Facility>()
	let alerts = List<Alert>()
Zach Knox's avatar
Zach Knox committed
17
18
19
20
21
	@objc dynamic var lastUpdated = Date()
	@objc dynamic let id = 0
}


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

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

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

Zach Knox's avatar
Zach Knox committed
40
	var filters = Filters()
41
	
42
43
44
45
	override var preferredStatusBarStyle: UIStatusBarStyle {
		return .default
	}
	
46
	@IBOutlet var LeftButton: UIBarButtonItem!
Zach Knox's avatar
Zach Knox committed
47

48
49
50
51
	@IBAction func RightButton(_ sender: Any) {
	}
	@IBOutlet var RightButton: UIBarButtonItem!
	
52
53
	@IBOutlet var settingsButton: UIBarButtonItem!
	
54
	@IBOutlet var LocationsList: UICollectionView!
Zach Knox's avatar
Zach Knox committed
55

56
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
Zach Knox's avatar
Zach Knox committed
57

58
	@IBOutlet var favoritesControl: UISegmentedControl!
Zach Knox's avatar
Zach Knox committed
59
60
	var showFavorites = false

61
	@IBOutlet var LastUpdatedLabel: UIBarButtonItem!
62
63
    
    let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
64

Zach Knox's avatar
Zach Knox committed
65
	@IBAction func favoritesControlChanges(_ sender: Any) {
66
		switch self.favoritesControl.selectedSegmentIndex
Zach Knox's avatar
Zach Knox committed
67
68
69
		{
		case 0:
			showFavorites = false
70
			shownFacilities = filteredFacilities
Zach Knox's avatar
Zach Knox committed
71
		case 1:
72
            showFavorites = true
73
			shownFacilities = filterFacilitiesForFavorites()
Zach Knox's avatar
Zach Knox committed
74
75
		default:
			showFavorites = false
76
			shownFacilities = filteredFacilities
Zach Knox's avatar
Zach Knox committed
77
78
79
		}
		self.LocationsList.reloadData()
	}
80
81
82
83
84
85
86
87
88
89
90
    
    /**
     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
91
        favoriteFacilites = filteredFacilities.filter({ (facility: Facility) -> Bool in
92
93
94
95
96
            return Utilities.isFavoriteFacility(facility)
        })
        
        return favoriteFacilites
    }
Zach Knox's avatar
Zach Knox committed
97

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

119
	@IBAction func RefreshButton(_ sender: Any) {
Zach Knox's avatar
Zach Knox committed
120
		refresh(sender, forceUpdate: true)
121
	}
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
	
	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
142

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

Zach Knox's avatar
Zach Knox committed
227
		refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
228
		LocationsList.refreshControl = refreshControl
Zach Knox's avatar
Zach Knox committed
229
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
230

Zach Knox's avatar
Zach Knox committed
231
		refresh(self, forceUpdate: false)
Zach Knox's avatar
Zach Knox committed
232
		
233
		reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
234
		
235
	}
Zach Knox's avatar
Zach Knox committed
236
	
237
	func reloadWithFilters() {
Zach Knox's avatar
Zach Knox committed
238
239
		
		// Facilities
240
241
242
		filteredFacilities = filters.applyFiltersOnFacilities(facilitiesArray)
		shownFacilities = filteredFacilities
		favoritesControlChanges(self)
Zach Knox's avatar
Zach Knox committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
		
		// Alerts
		let shown = List<Alert>()
		let formatter = ISO8601DateFormatter()
		formatter.timeZone = TimeZone(identifier: "America/New_York")
		let now = Date()
		for alert in alertsList {
			if now.isGreaterThanDate(dateToCompare: formatter.date(from: alert.startDate)!)  && now.isLessThanDate(dateToCompare: formatter.date(from: alert.endDate)!) {
				shown.append(alert)
			}
		}
		currentAlerts = shown
		
		
257
258
		LocationsList.reloadData()
	}
Zac Wood's avatar
Zac Wood committed
259
260
261
262
263
264
265
266
267
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
268
269
270
271
272
273
274
275
276
277
    /**
     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>
278
279
		
		/*
280
281
282
283
284
285
286
287
288
289
290
291
292
293
        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
                })
            }
294

295
        } else {
296
297
298
299
300
301
302
303
304
305
306
307
308
		  */
		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
		})
309
        
Zac Wood's avatar
Zac Wood committed
310
        LocationsList.reloadData()
311
        return filtered
Zac Wood's avatar
Zac Wood committed
312
    }
Zach Knox's avatar
Zach Knox committed
313
	
314
315
316
317
	/*
	* Reloads data, either calling update() to attempt a download
	* or simply pulling from the realm
	*/
Zach Knox's avatar
Zach Knox committed
318
	func refresh(_ sender: Any, forceUpdate: Bool = true) {
Zach Knox's avatar
Zach Knox committed
319
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
320
321
322
323
324
325
326
327
		if(forceUpdate) {
			update(sender);
		}
		else {
			let results = realm.objects(FacilitiesModel.self)
			if results.count > 0 {
				let model = results[0]
				let facilities = model.facilities
Zach Knox's avatar
Zach Knox committed
328
				let alerts = model.alerts
Zach Knox's avatar
Zach Knox committed
329
330
				let lastUpdated = model.lastUpdated
				
Zach Knox's avatar
Zach Knox committed
331
				if((facilities.isEmpty && alerts.isEmpty) || lastUpdated.isLessThanDate(dateToCompare: Date(timeIntervalSinceNow: -86400.0))) {
Zach Knox's avatar
Zach Knox committed
332
333
334
335
					update(sender)
				}
				else {
					facilitiesArray = facilities
Zach Knox's avatar
Zach Knox committed
336
					alertsList = alerts
Zach Knox's avatar
Zach Knox committed
337
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
Zach Knox's avatar
Zach Knox committed
338
339
340
341
342
343
344
				}
			}
			else {
				update(sender)
			}

		}
Zach Knox's avatar
Zach Knox committed
345
		
346
347
348
349
350
351
352
353
354
355
		
		// 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
356
357
		
		reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
358
359
		refreshControl.endRefreshing()
	}
Zach Knox's avatar
Zach Knox committed
360
	
361
362
363
364
	/*
	* Attempts to update facilitiesArray from the network
	* and place that new information into Realm
	*/
Zach Knox's avatar
Zach Knox committed
365
	func update(_ sender: Any) {
366
		SRCTNetworkController.performDownload { (facilities) in
Zach Knox's avatar
Zach Knox committed
367
368
369
370
371
372
373
374
375
			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
376
						self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
377
378
379
380
						self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
					}
					else {
						self.facilitiesArray = List<Facility>()
Zach Knox's avatar
Zach Knox committed
381
382
					}
				}
Zach Knox's avatar
Zach Knox committed
383
384
385
386
387
388
			}
			else {
				self.facilitiesArray = facilities!
				
				DispatchQueue.main.async {
					let date = Date()
Zach Knox's avatar
Zach Knox committed
389
					//self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
390
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(date)
Zach Knox's avatar
Zach Knox committed
391

Zach Knox's avatar
Zach Knox committed
392
393
					let results = self.realm.objects(FacilitiesModel.self)
					if results.count == 0 {
Zach Knox's avatar
Zach Knox committed
394
395
396
397
398
						let model = FacilitiesModel()
						for f in facilities! {
							model.facilities.append(f)
						}
						model.lastUpdated = date
Zach Knox's avatar
Zach Knox committed
399
400
401
402
403
404
405
						try! self.realm.write {
							self.realm.add(model)
						}
					}
					else {
						let fromRealm = results[0]
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
406
407
408
409
410
							fromRealm.facilities.removeAll()
							for f in facilities! {
								fromRealm.facilities.append(f)
							}
							fromRealm.lastUpdated = date
Zach Knox's avatar
Zach Knox committed
411
						}
Zach Knox's avatar
Zach Knox committed
412
413
					}
				}
Zach Knox's avatar
Zach Knox committed
414
			}
Zach Knox's avatar
Zach Knox committed
415
416
417
418
419
420
421
		}
		SRCTNetworkController.performAlertsDownload { (alerts) in
			if(alerts == nil) {
				DispatchQueue.main.async {
					let results = self.realm.objects(FacilitiesModel.self)
					if results.count > 0 {
						let model = results[0]
Zach Knox's avatar
Zach Knox committed
422
						self.alertsList = model.alerts
Zach Knox's avatar
Zach Knox committed
423
424
425
426
427
428
429
430
431
432
433
434
435
					}
					else {
						self.alertsList = List<Alert>()
					}
				}
			}
			else {
				self.alertsList = alerts!
				
				DispatchQueue.main.async {
					let results = self.realm.objects(FacilitiesModel.self)
					if results.count == 0 {
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
436
437
438
439
							let model = FacilitiesModel()
							for a in alerts! {
								model.alerts.append(a)
							}
Zach Knox's avatar
Zach Knox committed
440
441
442
443
444
445
							self.realm.add(model)
						}
					}
					else {
						let fromRealm = results[0]
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
446
447
448
449
							fromRealm.alerts.removeAll()
							for a in alerts! {
								fromRealm.alerts.append(a)
							}
Zach Knox's avatar
Zach Knox committed
450
451
452
453
						}
					}
				}
			}
454
		}
Zach Knox's avatar
Zach Knox committed
455
	}
Zac Wood's avatar
Zac Wood committed
456
    
457
458
459
460
461
462
463
464
465
	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
466
	
467
468
469
470
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
Zach Knox's avatar
Zach Knox committed
471

472
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
473
		if currentAlerts.count > 0 {
Zach Knox's avatar
Zach Knox committed
474
475
476
477
478
			return 2
		}
		else {
			return 1
		}
479
	}
Zach Knox's avatar
Zach Knox committed
480

481
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
Zach Knox's avatar
Zach Knox committed
482
483
484
485
486
		if(section == 1 || alertsList.count == 0) {
			return shownFacilities.count
		}
		else {
			// TODO: get current alerts, not just any alerts
Zach Knox's avatar
Zach Knox committed
487
			return currentAlerts.count
Zach Knox's avatar
Zach Knox committed
488
489
		}
		
490
	}
Zach Knox's avatar
Zach Knox committed
491

492
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
Zach Knox's avatar
Zach Knox committed
493
494
495
496
497
498
499
		
		if (indexPath.section == 1 || alertsList.count == 0) {
			let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! FacilityCollectionViewCell
			/*
			let windowRect = self.view.window!.frame
			let windowWidth = windowRect.size.width
			if(windowWidth <= 320) {
Zach Knox's avatar
Zach Knox committed
500
			cell.frame.size.width = 280
Zach Knox's avatar
Zach Knox committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
			}
			*/
			//Get tap of the cell
			cell.tapRecognizer.addTarget(self, action: #selector(FacilitiesListViewController.tapRecognizer(_:)))
			cell.gestureRecognizers = []
			cell.gestureRecognizers?.append(cell.tapRecognizer)
			
			
			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() || showFavorites {
			dataArray = placeOpenFacilitiesFirstInArray(filteredFacilities)
			} else {
			dataArray = placeOpenFacilitiesFirstInArray(facilitiesArray)
			}
			*/
			
			
			
			facility = shownFacilities[indexPath.row]
			
			cell.facility = facility
			
			//set labels
			cell.nameLabel.text = facility.facilityName
			cell.categoryLabel.text = facility.category?.categoryName.uppercased()
			
			cell.openClosedLabel.text = Utilities.openOrClosedUntil(facility)
			
			cell.timeDescriptionLabel.text = facility.facilityLocation?.building
			
			//change appearence based on open state
			let open = Utilities.isOpen(facility: facility)
			if(open == true) {
				//cell.openClosedLabel.text = "Open"
				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)
				cell.backgroundColor = UIColor(red:0.00, green:0.40, blue:0.20, alpha:1.0)
			} else {
				//cell.openClosedLabel.text = "Closed"
				cell.openClosedLabel.textColor = UIColor.white
				cell.openClosedLabel.backgroundColor = UIColor.black
				//cell.openClosedLabel.backgroundColor = UIColor.red
				cell.backgroundColor = UIColor.red
				
			}
			
			//Accessibility
			//TODO: FIX THIS
			cell.accessibilityLabel = cell.nameLabel.text! + ", Currently " + cell.openClosedLabel.text! + "." + cell.timeDescriptionLabel.text!
			cell.accessibilityHint = "Double Tap to view details"
			
			
			self.reloadInputViews()
			return cell
Zach Knox's avatar
Zach Knox committed
560
		}
Zach Knox's avatar
Zach Knox committed
561
562
		else {
			// Do Alerts things here
Zach Knox's avatar
Zach Knox committed
563
564
			let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Alert Cell", for: indexPath) as! AlertCollectionViewCell
			
Zach Knox's avatar
Zach Knox committed
565
566
567
568
569
570
571
572
573
574
575
576
			switch currentAlerts[indexPath.row].urgency {
			case "info":
				cell.imageView.image = #imageLiteral(resourceName: "info")
			case "minor":
				cell.imageView.image = #imageLiteral(resourceName: "minor")
			case "major":
				cell.imageView.image = #imageLiteral(resourceName: "major")
			case "emergency":
				cell.imageView.image = #imageLiteral(resourceName: "emergency")
			default:
				cell.imageView.image = #imageLiteral(resourceName: "major")
			}
Zach Knox's avatar
Zach Knox committed
577
578
579
			cell.messageLabel.text = currentAlerts[indexPath.row].message
			
			return cell
580
		}
Zach Knox's avatar
Zach Knox committed
581

582
	}
Zach Knox's avatar
Zach Knox committed
583

584
585
	
	//unused
Zach Knox's avatar
Zach Knox committed
586
	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
587
588
589
590
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
591
			return placeOpenFacilitiesFirstInArray(filteredFacilities)
Zach Knox's avatar
Zach Knox committed
592
		}
Zach Knox's avatar
Zach Knox committed
593
594


Zach Knox's avatar
Zach Knox committed
595
	}
596
	
597
	//unused
Zac Wood's avatar
Zac Wood committed
598
599
600
	// 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
601
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
602
603
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
604

605
606
607
608
609
610
611
612
613
614
615
		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
616

617
	//unused
618
619
620
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
621

622
623
624
625
626
627
628
629
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
630

631
632
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
633
634


635
636
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
637
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zach Knox's avatar
Zach Knox committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
    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.
    }
663
	
664
665
666
667
	// MARK: - Peek and Pop
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
		guard let indexPath = LocationsList?.indexPathForItem(at: location) else { return nil }
668
669
		let cell = LocationsList?.cellForItem(at: indexPath) as! FacilityCollectionViewCell
		guard let detailView = storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController else { return nil }
670
671
		
		detailView.facility = cell.facility
Zach Knox's avatar
Zach Knox committed
672

673
674
675
676
		return detailView
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
Zach Knox's avatar
Zach Knox committed
677
678
679
680
681
		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)
682
683
	}
	
684
}
Zac Wood's avatar
Zac Wood committed
685
686
687
688
689

// 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 ?? ""
Zach Knox's avatar
Zach Knox committed
690
        shownFacilities = filterFacilitiesForSearchText(searchText)
Zac Wood's avatar
Zac Wood committed
691
692
693
    }
}

Zach Knox's avatar
Zach Knox committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
// based on https://stackoverflow.com/questions/26198526/nsdate-comparison-using-swift
extension Date {
	func isGreaterThanDate(dateToCompare: Date) -> Bool {
		//Declare Variables
		var isGreater = false
		
		//Compare Values
		if self.compare(dateToCompare) == ComparisonResult.orderedDescending {
			isGreater = true
		}
		
		//Return Result
		return isGreater
	}
	
	func isLessThanDate(dateToCompare: Date) -> Bool {
		//Declare Variables
		var isLess = false
		
		//Compare Values
		if self.compare(dateToCompare) == ComparisonResult.orderedAscending {
			isLess = true
		}
		
		//Return Result
		return isLess
	}
	
	func equalToDate(dateToCompare: Date) -> Bool {
		//Declare Variables
		var isEqualTo = false
		
		//Compare Values
		if self.compare(dateToCompare) == ComparisonResult.orderedSame {
			isEqualTo = true
		}
		
		//Return Result
		return isEqualTo
	}
}

Zach Knox's avatar
Zach Knox committed
736
737