FacilitiesListViewController.swift 25.7 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, UICollectionViewDelegateFlowLayout {
23

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
	// Tell Realm to use this new configuration object for the default Realm
	let realm = try! Realm(configuration: Realm.Configuration(
		// Set the new schema version. This must be greater than the previously used
		// version (if you've never set a schema version before, the version is 0).
		schemaVersion: 1,
		
		// Set the block which will be called automatically when opening a Realm with
		// a schema version lower than the one set above
		migrationBlock: { migration, oldSchemaVersion in
			// We haven’t migrated anything yet, so oldSchemaVersion == 0
			if (oldSchemaVersion < 1) {
				migration.enumerateObjects(ofType: "FacilitiesModel", { (oldObject, newObject) in
					newObject!["alerts"] = List<Alert>()
				})
			}
	}))
Zach Knox's avatar
Zach Knox committed
40

Zach Knox's avatar
Zach Knox committed
41
	var facilitiesArray = List<Facility>()
Zach Knox's avatar
Zach Knox committed
42
	var alertsList = List<Alert>()
Zach Knox's avatar
Zach Knox committed
43
44
	
	var currentAlerts = List<Alert>()
45
46
    
    // array of facilities that pass the current filters
Zac Wood's avatar
Zac Wood committed
47
    var filteredFacilities = List<Facility>()
48
49
50
	
	// List which actually pertains to what is shown
	var shownFacilities = List<Facility>()
Zac Wood's avatar
Zac Wood committed
51
    
52
    // passing in nil sets the search controller to be this controller
Zac Wood's avatar
Zac Wood committed
53
54
    let searchController = UISearchController(searchResultsController: nil)

Zach Knox's avatar
Zach Knox committed
55
	var filters = Filters()
56
	
57
58
59
60
	override var preferredStatusBarStyle: UIStatusBarStyle {
		return .default
	}
	
61
62
	@IBOutlet var LeftButton: UIBarButtonItem!
	
63
64
	@IBOutlet var settingsButton: UIBarButtonItem!
	
65
	@IBOutlet var LocationsList: UICollectionView!
Zach Knox's avatar
Zach Knox committed
66

67
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
68
	
69
	@IBOutlet var favoritesControl: UISegmentedControl!
Zach Knox's avatar
Zach Knox committed
70
71
	var showFavorites = false

72
	@IBOutlet var LastUpdatedLabel: UIBarButtonItem!
73
74
    
    let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
75

Zach Knox's avatar
Zach Knox committed
76
	@IBAction func favoritesControlChanges(_ sender: Any) {
77
		switch self.favoritesControl.selectedSegmentIndex
Zach Knox's avatar
Zach Knox committed
78
79
80
		{
		case 0:
			showFavorites = false
81
			shownFacilities = filteredFacilities
Zach Knox's avatar
Zach Knox committed
82
		case 1:
83
            showFavorites = true
84
			shownFacilities = filterFacilitiesForFavorites()
Zach Knox's avatar
Zach Knox committed
85
86
		default:
			showFavorites = false
87
			shownFacilities = filteredFacilities
Zach Knox's avatar
Zach Knox committed
88
89
90
		}
		self.LocationsList.reloadData()
	}
91
92
93
94
95
96
97
98
99
100
101
    
    /**
     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
102
        favoriteFacilites = filteredFacilities.filter({ (facility: Facility) -> Bool in
103
104
105
106
107
            return Utilities.isFavoriteFacility(facility)
        })
        
        return favoriteFacilites
    }
Zach Knox's avatar
Zach Knox committed
108

109
	override func viewWillLayoutSubviews() {
110
		//LocationsListLayout.itemSize.width = getCellWidth()
Zach Knox's avatar
Zach Knox committed
111
		LocationsListLayout.invalidateLayout()
112
		LocationsList.reloadData()
Zach Knox's avatar
Zach Knox committed
113
114
	}
	
115
	/*
Zach Knox's avatar
Zach Knox committed
116
	func getCellWidth() -> CGFloat {
117
118
		let windowWidth = self.view.frame.size.width
		
Zach Knox's avatar
Zach Knox committed
119
120
		if(windowWidth < 640) {
			return windowWidth - 20
121
122
		}
		else if(windowWidth >= 640 && windowWidth < 1024) {
Zach Knox's avatar
Zach Knox committed
123
			return (windowWidth / 2) - 15
124
125
		}
		else if(windowWidth >= 1024) {
Zach Knox's avatar
Zach Knox committed
126
			return (windowWidth / 3) - 15
127
128
		}
		
Zach Knox's avatar
Zach Knox committed
129
		return 0
130
	}
131
	*/
Zach Knox's avatar
Zach Knox committed
132

133
	@IBAction func RefreshButton(_ sender: Any) {
Zach Knox's avatar
Zach Knox committed
134
		refresh(sender, forceUpdate: true)
135
		reloadWithFilters()
136
	}
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
	
	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
				}
			}
152
153
154
155
156
157
			for f in filters.onlyFromCampuses {
				if(f.value != true) {
					LeftButton.title = "Filter (On)"
					return
				}
			}
Zach Knox's avatar
Zach Knox committed
158
159
160
161
162
163
			for f in filters.showAlerts {
				if(f.value != true) {
					LeftButton.title = "Filter (On)"
					return
				}
			}
164
165
166
167
168
			LeftButton.title = "Filter"
			return
		}
		LeftButton.title = "Filter (On)"
	}
Zach Knox's avatar
Zach Knox committed
169

170
171
	override func viewWillAppear(_ animated: Bool) {
		LastUpdatedLabel.isEnabled = false
172
		checkFilterState()
173
		reloadWithFilters()
174
175
	}
	
Zach Knox's avatar
Zach Knox committed
176
	@objc func tapRecognizer(_ sender: UITapGestureRecognizer) {
Zach Knox's avatar
Zach Knox committed
177
178
179
		
		let tapLocation = sender.location(in: LocationsList)
		let indexPath = LocationsList.indexPathForItem(at: tapLocation)
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
		
		if(indexPath != nil) {
			if(indexPath?.section == 1 || currentAlerts.count == 0) {
				let destination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController
				destination?.currentViewController = self.storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController
				let tapped = self.LocationsList.cellForItem(at: indexPath!) as! FacilityCollectionViewCell
				(destination?.currentViewController as? FacilityDetailViewController)?.facility = tapped.facility
				self.presentDetailView(destination!)
			}
			else {
				let destination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController
				destination?.currentViewController = self.storyboard?.instantiateViewController(withIdentifier: "alertDetail") as? AlertDetailViewController
				let tapped = self.LocationsList.cellForItem(at: indexPath!) as! AlertCollectionViewCell
				(destination?.currentViewController as? AlertDetailViewController)?.alert = tapped.alert
				self.presentDetailView(destination!)
			}
Zach Knox's avatar
Zach Knox committed
196
		}
197

Zach Knox's avatar
Zach Knox committed
198
199
	}
	
200
	func presentDetailView(_ destination: PullingViewController) {
Zach Knox's avatar
Zach Knox committed
201
202
203
		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
204
205
206
207
			destination.modalPresentationStyle = .popover
			let popoverController = destination.popoverPresentationController
			popoverController?.permittedArrowDirections = .any
			popoverController?.sourceView = destination.view
Zac Wood's avatar
Zac Wood committed
208
209
210
211
212
213
214
215
            
            // 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
216
217
218
219
220
		}
		else {
			let destDelegate = DeckTransitioningDelegate()
			destination.modalPresentationStyle = .custom
			destination.transitioningDelegate = destDelegate
Zac Wood's avatar
Zac Wood committed
221
222
223
224
225
226
227
228
            
            // 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
229
		}
Zac Wood's avatar
Zac Wood committed
230
231
        
        
Zach Knox's avatar
Zach Knox committed
232
	}
Zac Wood's avatar
Zac Wood committed
233
234
235
236
237
238
239
240
241
    
    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
242
243
	
	override func viewDidLoad() {
244
245
        super.viewDidLoad()
		
246
247
		self.definesPresentationContext = true
		
Zach Knox's avatar
Zach Knox committed
248
		if(traitCollection.forceTouchCapability == .available) {
249
250
			registerForPreviewing(with: self, sourceView: self.LocationsList!)
		}
Zach Knox's avatar
Zach Knox committed
251
252
        
        navigationItem.title = "What's Open"
253
		navigationController?.navigationBar.prefersLargeTitles = true
254
255
		navigationItem.largeTitleDisplayMode = .always
		
Zac Wood's avatar
Zac Wood committed
256
        configureSearchController()
Zach Knox's avatar
Zach Knox committed
257
		
258
		LocationsListLayout.invalidateLayout()
Zach Knox's avatar
Zach Knox committed
259
		
260
261
262
		settingsButton.accessibilityLabel = "Settings"
		LastUpdatedLabel.accessibilityHint = ""
		
263
		LocationsListLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
Zach Knox's avatar
Zach Knox committed
264

Zach Knox's avatar
Zach Knox committed
265
		refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
266
		LocationsList.refreshControl = refreshControl
Zach Knox's avatar
Zach Knox committed
267
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
268

Zach Knox's avatar
Zach Knox committed
269
		refresh(self, forceUpdate: false)
Zach Knox's avatar
Zach Knox committed
270
		
271
		reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
272
		
273
	}
Zach Knox's avatar
Zach Knox committed
274
	
275
	func reloadWithFilters() {
Zach Knox's avatar
Zach Knox committed
276
277
		
		// Facilities
278
279
280
		filteredFacilities = filters.applyFiltersOnFacilities(facilitiesArray)
		shownFacilities = filteredFacilities
		favoritesControlChanges(self)
Zach Knox's avatar
Zach Knox committed
281
282
283
284
285
286
287
288
		
		// 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)!) {
Zach Knox's avatar
Zach Knox committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
				switch alert.urgency {
				case "info":
					if(filters.showAlerts["Informational"])! {
						shown.append(alert)
					}
				case "minor":
					if(filters.showAlerts["Minor Alerts"])! {
						shown.append(alert)
					}
				case "major":
					if(filters.showAlerts["Major Alerts"])! {
						shown.append(alert)
					}
				default:
					shown.append(alert)
				}
Zach Knox's avatar
Zach Knox committed
305
306
307
308
309
			}
		}
		currentAlerts = shown
		
		
310
311
		LocationsList.reloadData()
	}
Zac Wood's avatar
Zac Wood committed
312
313
314
315
316
317
318
319
320
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
321
322
323
324
325
326
327
328
329
330
    /**
     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>
331
332
		
		/*
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        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
                })
            }
347

348
        } else {
349
350
351
352
353
354
355
356
357
358
359
360
361
		  */
		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
		})
362
        
Zac Wood's avatar
Zac Wood committed
363
        LocationsList.reloadData()
364
        return filtered
Zac Wood's avatar
Zac Wood committed
365
    }
Zach Knox's avatar
Zach Knox committed
366
	
367
368
369
370
	/*
	* Reloads data, either calling update() to attempt a download
	* or simply pulling from the realm
	*/
371
	@objc func refresh(_ sender: Any, forceUpdate: Bool = true) {
Zach Knox's avatar
Zach Knox committed
372
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
373
374
375
376
377
378
379
380
		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
381
				let alerts = model.alerts
Zach Knox's avatar
Zach Knox committed
382
383
				let lastUpdated = model.lastUpdated
				
384
				if((facilities.isEmpty && alerts.isEmpty) || lastUpdated.isLessThanDate(dateToCompare: Date(timeIntervalSinceNow: -43200.0))) {
Zach Knox's avatar
Zach Knox committed
385
386
387
388
					update(sender)
				}
				else {
					facilitiesArray = facilities
Zach Knox's avatar
Zach Knox committed
389
					alertsList = alerts
Zach Knox's avatar
Zach Knox committed
390
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
Zach Knox's avatar
Zach Knox committed
391
392
393
394
395
396
397
				}
			}
			else {
				update(sender)
			}

		}
Zach Knox's avatar
Zach Knox committed
398
		
399
		
400
401
402
403
404
405
406
		updateFiltersLists()
		
		reloadWithFilters()
		refreshControl.endRefreshing()
	}
	
	func updateFiltersLists() {
407
408
409
410
411
412
413
414
		// 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)!)
			}
415
416
417
			if(!filters.onlyFromCampuses.keys.contains((f.facilityLocation?.campus)!)) {
				filters.onlyFromCampuses.updateValue(true, forKey: (f.facilityLocation?.campus)!)
			}
418
		}
Zach Knox's avatar
Zach Knox committed
419
	}
Zach Knox's avatar
Zach Knox committed
420
	
421
422
423
424
	/*
	* Attempts to update facilitiesArray from the network
	* and place that new information into Realm
	*/
Zach Knox's avatar
Zach Knox committed
425
	func update(_ sender: Any) {
426
		SRCTNetworkController.performDownload { (facilities) in
Zach Knox's avatar
Zach Knox committed
427
428
429
430
431
432
433
434
435
			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
436
						self.updateFiltersLists()
437
						self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
438
439
440
441
						self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
					}
					else {
						self.facilitiesArray = List<Facility>()
Zach Knox's avatar
Zach Knox committed
442
443
					}
				}
Zach Knox's avatar
Zach Knox committed
444
445
446
447
448
449
450
			}
			else {
				self.facilitiesArray = facilities!
				
				DispatchQueue.main.async {
					let date = Date()
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(date)
Zach Knox's avatar
Zach Knox committed
451

Zach Knox's avatar
Zach Knox committed
452
453
					let results = self.realm.objects(FacilitiesModel.self)
					if results.count == 0 {
Zach Knox's avatar
Zach Knox committed
454
455
456
457
458
						let model = FacilitiesModel()
						for f in facilities! {
							model.facilities.append(f)
						}
						model.lastUpdated = date
Zach Knox's avatar
Zach Knox committed
459
460
461
462
463
464
465
						try! self.realm.write {
							self.realm.add(model)
						}
					}
					else {
						let fromRealm = results[0]
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
466
467
468
469
470
							fromRealm.facilities.removeAll()
							for f in facilities! {
								fromRealm.facilities.append(f)
							}
							fromRealm.lastUpdated = date
Zach Knox's avatar
Zach Knox committed
471
						}
Zach Knox's avatar
Zach Knox committed
472
					}
473
474
					self.updateFiltersLists()
					self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
475
				}
Zach Knox's avatar
Zach Knox committed
476
			}
Zach Knox's avatar
Zach Knox committed
477
478
479
480
481
482
483
		}
		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
484
						self.alertsList = model.alerts
Zach Knox's avatar
Zach Knox committed
485
486
487
488
489
490
491
492
493
494
495
496
497
					}
					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
498
499
500
501
							let model = FacilitiesModel()
							for a in alerts! {
								model.alerts.append(a)
							}
Zach Knox's avatar
Zach Knox committed
502
503
504
505
506
507
							self.realm.add(model)
						}
					}
					else {
						let fromRealm = results[0]
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
508
509
510
511
							fromRealm.alerts.removeAll()
							for a in alerts! {
								fromRealm.alerts.append(a)
							}
Zach Knox's avatar
Zach Knox committed
512
513
						}
					}
514
					self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
515
516
				}
			}
517
		}
Zach Knox's avatar
Zach Knox committed
518
	}
Zac Wood's avatar
Zac Wood committed
519
    
520
521
522
523
524
525
526
527
528
	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
529
	
530
531
532
533
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
Zach Knox's avatar
Zach Knox committed
534

535
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
536
		if currentAlerts.count > 0 {
Zach Knox's avatar
Zach Knox committed
537
538
539
540
541
			return 2
		}
		else {
			return 1
		}
542
	}
Zach Knox's avatar
Zach Knox committed
543

544
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
Zach Knox's avatar
Zach Knox committed
545
		if(section == 1 || currentAlerts.count == 0) {
Zach Knox's avatar
Zach Knox committed
546
547
548
549
			return shownFacilities.count
		}
		else {
			// TODO: get current alerts, not just any alerts
Zach Knox's avatar
Zach Knox committed
550
			return currentAlerts.count
Zach Knox's avatar
Zach Knox committed
551
552
		}
		
553
	}
Zach Knox's avatar
Zach Knox committed
554

555
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
Zach Knox's avatar
Zach Knox committed
556
		
Zach Knox's avatar
Zach Knox committed
557
		if (indexPath.section == 1 || currentAlerts.count == 0) {
Zach Knox's avatar
Zach Knox committed
558
559
560
561
562
			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
563
			cell.frame.size.width = 280
Zach Knox's avatar
Zach Knox committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
			}
			*/
			//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
623
		}
Zach Knox's avatar
Zach Knox committed
624
625
		else {
			// Do Alerts things here
Zach Knox's avatar
Zach Knox committed
626
			let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Alert Cell", for: indexPath) as! AlertCollectionViewCell
627
			cell.viewWidth = self.view.frame.width
628
629
630
631
			cell.alert = currentAlerts[indexPath.row]
			cell.tapRecognizer.addTarget(self, action: #selector(FacilitiesListViewController.tapRecognizer(_:)))
			cell.gestureRecognizers = []
			cell.gestureRecognizers?.append(cell.tapRecognizer)
Zach Knox's avatar
Zach Knox committed
632
			
Zach Knox's avatar
Zach Knox committed
633
634
635
			switch currentAlerts[indexPath.row].urgency {
			case "info":
				cell.imageView.image = #imageLiteral(resourceName: "info")
636
				cell.imageView.accessibilityLabel = "Info"
Zach Knox's avatar
Zach Knox committed
637
638
			case "minor":
				cell.imageView.image = #imageLiteral(resourceName: "minor")
639
				cell.imageView.accessibilityLabel = "Minor Alert"
Zach Knox's avatar
Zach Knox committed
640
641
			case "major":
				cell.imageView.image = #imageLiteral(resourceName: "major")
642
				cell.imageView.accessibilityLabel = "Major Alert"
Zach Knox's avatar
Zach Knox committed
643
644
			case "emergency":
				cell.imageView.image = #imageLiteral(resourceName: "emergency")
645
				cell.imageView.accessibilityLabel = "Emergency Alert"
Zach Knox's avatar
Zach Knox committed
646
647
			default:
				cell.imageView.image = #imageLiteral(resourceName: "major")
648
				cell.imageView.accessibilityLabel = "Alert"
Zach Knox's avatar
Zach Knox committed
649
			}
Zach Knox's avatar
Zach Knox committed
650
			cell.messageLabel.text = currentAlerts[indexPath.row].message
651
652

			
Zach Knox's avatar
Zach Knox committed
653
			return cell
654
		}
Zach Knox's avatar
Zach Knox committed
655

656
	}
657
658
	
	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
Zach Knox's avatar
Zach Knox committed
659
		if(indexPath.section == 1 || currentAlerts.count == 0) {
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
			let height = LocationsListLayout.itemSize.height
			let width: CGFloat
			
			let windowWidth = self.view.frame.size.width
			
			if(windowWidth < 640) {
				width = windowWidth - 20
			}
			else if(windowWidth >= 640 && windowWidth < 1024) {
				width = (windowWidth / 2) - 15
			}
			else if(windowWidth >= 1024) {
				width = (windowWidth / 3) - 15
			}
			else {
				width = windowWidth - 20
			}
			
			return CGSize(width: width, height: height)
		}
		else {
681
			return CGSize(width: self.view.frame.size.width, height: 43)
682
683
684
685
686
687
688
689
690
691
		}
	}

	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
		var sectionInsets = LocationsListLayout.sectionInset
		if(section != 1 && alertsList.count != 0) {
			sectionInsets.top = 0
		}
		return sectionInsets
	}
Zach Knox's avatar
Zach Knox committed
692

693
694
	
	//unused
Zach Knox's avatar
Zach Knox committed
695
	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
696
697
698
699
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
700
			return placeOpenFacilitiesFirstInArray(filteredFacilities)
Zach Knox's avatar
Zach Knox committed
701
		}
Zach Knox's avatar
Zach Knox committed
702
703


Zach Knox's avatar
Zach Knox committed
704
	}
705
	
706
	//unused
Zac Wood's avatar
Zac Wood committed
707
708
709
	// 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
710
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
711
712
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
713

714
715
716
717
718
719
720
721
722
723
724
		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
725

726
	//unused
727
728
729
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
730

731
732
733
734
735
736
737
738
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
739

740
741
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
742
743


744
745
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
746
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zach Knox's avatar
Zach Knox committed
747
748
749
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        if(segue.identifier == "toDetailView") {
750
751
752
            let destination = segue.destination as! PullingViewController
			var destChild = destination.childViewControllers[0] as! FacilityDetailViewController
			destChild = self.storyboard?.instantiateViewController(withIdentifier: "detailView") as! FacilityDetailViewController
Zach Knox's avatar
Zach Knox committed
753
754
755
            let destDelegate = DeckTransitioningDelegate()
            destination.transitioningDelegate = destDelegate
            let tapped = sender as! FacilityCollectionViewCell //this is probably a bad idea just FYI future me
756
			destChild.facility = tapped.facility
Zach Knox's avatar
Zach Knox committed
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773

            // 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.
    }
774
	
775
776
777
778
	// MARK: - Peek and Pop
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
		guard let indexPath = LocationsList?.indexPathForItem(at: location) else { return nil }
779
780
		let cell = LocationsList?.cellForItem(at: indexPath) as! FacilityCollectionViewCell
		guard let detailView = storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController else { return nil }
781
782
		
		detailView.facility = cell.facility
Zach Knox's avatar
Zach Knox committed
783

784
785
786
787
		return detailView
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
Zach Knox's avatar
Zach Knox committed
788
789
790
791
792
		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)
793
794
	}
	
795
}
Zac Wood's avatar
Zac Wood committed
796
797
798
799
800

// 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
801
        shownFacilities = filterFacilitiesForSearchText(searchText)
Zac Wood's avatar
Zac Wood committed
802
803
804
    }
}

Zach Knox's avatar
Zach Knox committed
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
// 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
847
848