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

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

Zach Knox's avatar
Zach Knox committed
13
14
//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
	// 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).
28
29
30
31
32
		schemaVersion: 3,
		// We replace the data stored every 12 hours, do we _really_ need to worry about schema updates?
		// I say nay.
		deleteRealmIfMigrationNeeded: true
	  ))
Zach Knox's avatar
Zach Knox committed
33

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

Zach Knox's avatar
Zach Knox committed
48
	var filters = Filters()
49
	
50
51
52
53
	override var preferredStatusBarStyle: UIStatusBarStyle {
		return .default
	}
	
54
55
	@IBOutlet var LeftButton: UIBarButtonItem!
	
56
57
	@IBOutlet var settingsButton: UIBarButtonItem!
	
58
	@IBOutlet var LocationsList: UICollectionView!
Zach Knox's avatar
Zach Knox committed
59

60
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
61
	
62
	@IBOutlet var favoritesControl: UISegmentedControl!
Zach Knox's avatar
Zach Knox committed
63
64
	var showFavorites = false

65
	@IBOutlet var LastUpdatedLabel: UIBarButtonItem!
66
67
    
    let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
68

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

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

126
	@IBAction func RefreshButton(_ sender: Any) {
Zach Knox's avatar
Zach Knox committed
127
		refresh(sender, forceUpdate: true)
128
		reloadWithFilters()
129
	}
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
	
	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
				}
			}
145
146
147
148
149
150
			for f in filters.onlyFromCampuses {
				if(f.value != true) {
					LeftButton.title = "Filter (On)"
					return
				}
			}
151
152
153
154
155
			LeftButton.title = "Filter"
			return
		}
		LeftButton.title = "Filter (On)"
	}
Zach Knox's avatar
Zach Knox committed
156

157
158
	override func viewWillAppear(_ animated: Bool) {
		LastUpdatedLabel.isEnabled = false
159
		checkFilterState()
160
		reloadWithFilters()
161
162
	}
	
Zach Knox's avatar
Zach Knox committed
163
	@objc func tapRecognizer(_ sender: UITapGestureRecognizer) {
Zach Knox's avatar
Zach Knox committed
164
165
166
		
		let tapLocation = sender.location(in: LocationsList)
		let indexPath = LocationsList.indexPathForItem(at: tapLocation)
167
168
169
		
		if(indexPath != nil) {
			if(indexPath?.section == 1 || currentAlerts.count == 0) {
170
				let destination =  self.storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController
171
				let tapped = self.LocationsList.cellForItem(at: indexPath!) as! FacilityCollectionViewCell
172
173
				destination?.facility = tapped.facility
				self.presentDetailView(destination!, tapped: tapped)
174
175
			}
			else {
176
				let destination = self.storyboard?.instantiateViewController(withIdentifier: "alertDetail") as? AlertDetailViewController
177
				let tapped = self.LocationsList.cellForItem(at: indexPath!) as! AlertCollectionViewCell
178
179
				destination?.alert = tapped.alert
				self.presentDetailView(destination!, tapped: tapped)
180
			}
Zach Knox's avatar
Zach Knox committed
181
		}
182

Zach Knox's avatar
Zach Knox committed
183
184
	}
	
185
	func presentDetailView(_ destination: UIViewController, tapped: UICollectionViewCell) {
Zach Knox's avatar
Zach Knox committed
186
187
188
		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
189
190
191
			destination.modalPresentationStyle = .popover
			let popoverController = destination.popoverPresentationController
			popoverController?.permittedArrowDirections = .any
192
193
			popoverController?.sourceView = tapped.contentView
			popoverController?.sourceRect = tapped.bounds
Zac Wood's avatar
Zac Wood committed
194
195
196
197
198
199
200
201
            
            // 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
202
203
		}
		else {
204
205
			let finalDestination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController // Fox only, no items
			finalDestination?.currentViewController = destination
Zach Knox's avatar
Zach Knox committed
206
			let destDelegate = DeckTransitioningDelegate()
207
208
			finalDestination?.modalPresentationStyle = .custom
			finalDestination?.transitioningDelegate = destDelegate
Zac Wood's avatar
Zac Wood committed
209
210
211
            
            // present the detail view over the search controller if we're searching
            if searchController.isActive {
212
				searchController.present(finalDestination!, animated: true, completion: nil)
Zac Wood's avatar
Zac Wood committed
213
214
            }
            else {
215
				present(finalDestination!, animated: true, completion: nil)
Zac Wood's avatar
Zac Wood committed
216
            }
Zach Knox's avatar
Zach Knox committed
217
		}
Zac Wood's avatar
Zac Wood committed
218
219
        
        
Zach Knox's avatar
Zach Knox committed
220
	}
Zac Wood's avatar
Zac Wood committed
221
222
223
224
225
226
227
228
229
    
    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
230
231
	
	override func viewDidLoad() {
232
233
        super.viewDidLoad()
		
234
235
		self.definesPresentationContext = true
		
Zach Knox's avatar
Zach Knox committed
236
		if(traitCollection.forceTouchCapability == .available) {
237
238
			registerForPreviewing(with: self, sourceView: self.LocationsList!)
		}
Zach Knox's avatar
Zach Knox committed
239
        
Zac Wood's avatar
Zac Wood committed
240
        
Zach Knox's avatar
Zach Knox committed
241
        navigationItem.title = "What's Open"
242
		navigationController?.navigationBar.prefersLargeTitles = true
243
244
		navigationItem.largeTitleDisplayMode = .always
		
Zac Wood's avatar
Zac Wood committed
245
        configureSearchController()
Zach Knox's avatar
Zach Knox committed
246
		
247
		LocationsListLayout.invalidateLayout()
Zach Knox's avatar
Zach Knox committed
248
		
249
250
251
		settingsButton.accessibilityLabel = "Settings"
		LastUpdatedLabel.accessibilityHint = ""
		
252
		LocationsListLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
Zach Knox's avatar
Zach Knox committed
253

Zach Knox's avatar
Zach Knox committed
254
		refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
255
		LocationsList.refreshControl = refreshControl
Zach Knox's avatar
Zach Knox committed
256
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
257

Zach Knox's avatar
Zach Knox committed
258
		refresh(self, forceUpdate: false)
Zach Knox's avatar
Zach Knox committed
259
		
260
		reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
261
		
262
	}
Zach Knox's avatar
Zach Knox committed
263
	
264
	func reloadWithFilters() {
Zach Knox's avatar
Zach Knox committed
265
266
		
		// Facilities
267
268
269
		filteredFacilities = filters.applyFiltersOnFacilities(facilitiesArray)
		shownFacilities = filteredFacilities
		favoritesControlChanges(self)
Zach Knox's avatar
Zach Knox committed
270
271
272
273
274
275
		
		// Alerts
		let shown = List<Alert>()
		let formatter = ISO8601DateFormatter()
		formatter.timeZone = TimeZone(identifier: "America/New_York")
		let now = Date()
276
277
		let defaults = UserDefaults.standard
		let alertFilers = defaults.dictionary(forKey: "alerts") as! [String: Bool]?
Zach Knox's avatar
Zach Knox committed
278
279
		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
280
281
				switch alert.urgency {
				case "info":
Zach Knox's avatar
Zach Knox committed
282
					if(alertFilers!["informational"])! {
Zach Knox's avatar
Zach Knox committed
283
284
285
						shown.append(alert)
					}
				case "minor":
Zach Knox's avatar
Zach Knox committed
286
					if(alertFilers!["minor alerts"])! {
Zach Knox's avatar
Zach Knox committed
287
288
289
						shown.append(alert)
					}
				case "major":
Zach Knox's avatar
Zach Knox committed
290
					if(alertFilers!["major alerts"])! {
Zach Knox's avatar
Zach Knox committed
291
292
293
294
295
						shown.append(alert)
					}
				default:
					shown.append(alert)
				}
Zach Knox's avatar
Zach Knox committed
296
297
298
299
300
			}
		}
		currentAlerts = shown
		
		
301
302
		LocationsList.reloadData()
	}
Zac Wood's avatar
Zac Wood committed
303
304
305
306
307
308
309
310
311
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
312
313
314
315
316
317
318
319
320
321
    /**
     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>
322
323
		
		/*
324
325
326
327
328
329
330
331
332
333
334
335
336
337
        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
                })
            }
338

339
        } else {
340
341
342
343
344
345
346
347
348
		  */
		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
Jesse Scearce's avatar
Jesse Scearce committed
349
            let hasAbbreviation = facility.facilityLocation?.abbreviation.lowercased().contains(searchText.lowercased()) ?? false
350
			let hasCategory = facility.category?.categoryName.lowercased().contains(searchText.lowercased()) ?? false
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
			var hasTag = false
			for tag in facility.facilityTags! {
				if hasTag {
					break
				}
				if tag.tag.lowercased().contains(searchText.lowercased()) {
					hasTag = true
				}
			}
			var hasLabel = false
			for label in facility.labels! {
				if hasLabel {
					break
				}
				if label.tag.lowercased().contains(searchText.lowercased()) {
					hasLabel = true
				}
			}
Jesse Scearce's avatar
Jesse Scearce committed
369
			return hasName || hasBuilding || hasCategory || hasTag || hasAbbreviation
370
		})
371
        
Zac Wood's avatar
Zac Wood committed
372
        LocationsList.reloadData()
373
        return filtered
Zac Wood's avatar
Zac Wood committed
374
    }
Zach Knox's avatar
Zach Knox committed
375
	
376
377
378
379
	/*
	* Reloads data, either calling update() to attempt a download
	* or simply pulling from the realm
	*/
380
	@objc func refresh(_ sender: Any, forceUpdate: Bool = true) {
Zach Knox's avatar
Zach Knox committed
381
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
382
383
384
385
386
387
388
389
		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
390
				let alerts = model.alerts
Zach Knox's avatar
Zach Knox committed
391
392
				let lastUpdated = model.lastUpdated
				
393
				if((facilities.isEmpty && alerts.isEmpty) || lastUpdated.isLessThanDate(dateToCompare: Date(timeIntervalSinceNow: -43200.0))) {
Zach Knox's avatar
Zach Knox committed
394
395
396
397
					update(sender)
				}
				else {
					facilitiesArray = facilities
Zach Knox's avatar
Zach Knox committed
398
					alertsList = alerts
Zach Knox's avatar
Zach Knox committed
399
					self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(lastUpdated)
Zach Knox's avatar
Zach Knox committed
400
401
402
403
404
405
406
				}
			}
			else {
				update(sender)
			}

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

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

544
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
545
		if currentAlerts.count > 0 {
Zach Knox's avatar
Zach Knox committed
546
547
548
549
550
			return 2
		}
		else {
			return 1
		}
551
	}
Zach Knox's avatar
Zach Knox committed
552

553
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
Zach Knox's avatar
Zach Knox committed
554
		if(section == 1 || currentAlerts.count == 0) {
Zach Knox's avatar
Zach Knox committed
555
556
557
558
			return shownFacilities.count
		}
		else {
			// TODO: get current alerts, not just any alerts
Zach Knox's avatar
Zach Knox committed
559
			return currentAlerts.count
Zach Knox's avatar
Zach Knox committed
560
561
		}
		
562
	}
Zach Knox's avatar
Zach Knox committed
563

564
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
Zach Knox's avatar
Zach Knox committed
565
		
Zach Knox's avatar
Zach Knox committed
566
		if (indexPath.section == 1 || currentAlerts.count == 0) {
Zach Knox's avatar
Zach Knox committed
567
568
569
570
571
			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
572
			cell.frame.size.width = 280
Zach Knox's avatar
Zach Knox committed
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
			}
			*/
			//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
Zach Knox's avatar
Zach Knox committed
600
601
602
603
604
605
			var name = facility.facilityName
			let separator = name.index(of: "[")
			if separator != nil {
				name = String(name[..<separator!]).replacingOccurrences(of: "\\s+$",with: "", options: .regularExpression)
			}
			cell.nameLabel.text = name
Zach Knox's avatar
Zach Knox committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
			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
Eyad Hasan's avatar
Eyad Hasan committed
625
				cell.backgroundColor = UIColor(red:0.17, green:0.17, blue: 0.17, alpha: 1.0)
Zach Knox's avatar
Zach Knox committed
626
627
628
629
				
			}
			
			//Accessibility
630
			cell.accessibilityLabel = cell.nameLabel.text! + " " + cell.categoryLabel.text! + ", Currently " + cell.openClosedLabel.text! + ". Located in" + cell.timeDescriptionLabel.text!
Zach Knox's avatar
Zach Knox committed
631
632
633
			cell.accessibilityHint = "Double Tap to view details"
			
			
634
635
636
637
638
639
640
			//Shadows
			cell.layer.shadowColor = UIColor.black.cgColor
			cell.layer.shadowOffset = CGSize(width: 0, height: 3)
			cell.layer.shadowRadius = 7.0
			cell.layer.shadowOpacity = 0.4
			cell.layer.masksToBounds = false
			cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.layer.cornerRadius).cgPath
Zach Knox's avatar
Zach Knox committed
641
642
			self.reloadInputViews()
			return cell
Zach Knox's avatar
Zach Knox committed
643
		}
Zach Knox's avatar
Zach Knox committed
644
645
		else {
			// Do Alerts things here
Zach Knox's avatar
Zach Knox committed
646
			let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Alert Cell", for: indexPath) as! AlertCollectionViewCell
647
			cell.viewWidth = self.view.frame.width
648
649
650
651
			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
652
			
Zach Knox's avatar
Zach Knox committed
653
654
655
			switch currentAlerts[indexPath.row].urgency {
			case "info":
				cell.imageView.image = #imageLiteral(resourceName: "info")
656
				cell.imageView.accessibilityLabel = "Info"
Zach Knox's avatar
Zach Knox committed
657
658
			case "minor":
				cell.imageView.image = #imageLiteral(resourceName: "minor")
659
				cell.imageView.accessibilityLabel = "Minor Alert"
Zach Knox's avatar
Zach Knox committed
660
661
			case "major":
				cell.imageView.image = #imageLiteral(resourceName: "major")
662
				cell.imageView.accessibilityLabel = "Major Alert"
Zach Knox's avatar
Zach Knox committed
663
664
			case "emergency":
				cell.imageView.image = #imageLiteral(resourceName: "emergency")
665
				cell.imageView.accessibilityLabel = "Emergency Alert"
Zach Knox's avatar
Zach Knox committed
666
667
			default:
				cell.imageView.image = #imageLiteral(resourceName: "major")
668
				cell.imageView.accessibilityLabel = "Alert"
Zach Knox's avatar
Zach Knox committed
669
			}
Zach Knox's avatar
Zach Knox committed
670
			cell.messageLabel.text = currentAlerts[indexPath.row].message
671
672

			
Zach Knox's avatar
Zach Knox committed
673
			return cell
674
		}
Zach Knox's avatar
Zach Knox committed
675

676
	}
677
	
678
	// MARK - Collection View Cell Layout
679
	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
Zach Knox's avatar
Zach Knox committed
680
		if(indexPath.section == 1 || currentAlerts.count == 0) {
681
682
683
			let height = LocationsListLayout.itemSize.height
			let width: CGFloat
			
684
685
			let edgeInsets = self.view.safeAreaInsets
			let windowWidth = self.view.frame.size.width - edgeInsets.left - edgeInsets.right
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
			
			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 {
703
704
			let edgeInsets = self.view.safeAreaInsets
			return CGSize(width: self.view.frame.size.width - edgeInsets.left - edgeInsets.right, height: 43)
705
706
		}
	}
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
	
	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
		if(section == 1 || currentAlerts.count == 0) {
			return 15
		}
		else {
			return 0
		}
	}
	
	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
		if(section == 1 || currentAlerts.count == 0) {
			return 10
		}
		else {
			return 0
		}
	}
725
726
727

	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
		var sectionInsets = LocationsListLayout.sectionInset
Zach Knox's avatar
Zach Knox committed
728
		if(section != 1 && currentAlerts.count != 0) {
729
730
			sectionInsets.top = 0
		}
Zach Knox's avatar
Zach Knox committed
731
732
733
		else if currentAlerts.count == 0 {
			sectionInsets.top = 15
		}
734
735
		return sectionInsets
	}
Zach Knox's avatar
Zach Knox committed
736

737
738
	
	//unused
Zach Knox's avatar
Zach Knox committed
739
	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
740
741
742
743
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
744
			return placeOpenFacilitiesFirstInArray(filteredFacilities)
Zach Knox's avatar
Zach Knox committed
745
		}
Zach Knox's avatar
Zach Knox committed
746
747


Zach Knox's avatar
Zach Knox committed
748
	}
749
	
750
	//unused
Zac Wood's avatar
Zac Wood committed
751
752
753
	// 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
754
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
755
756
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
757

758
759
760
761
762
763
764
765
766
767
768
		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
769

770
	//unused
771
772
773
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
774

775
776
777
778
779
780
781
782
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
783

784
785
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
786
787


788
789
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
790
	//unused
Zach Knox's avatar
Zach Knox committed
791
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zach Knox's avatar
Zach Knox committed
792
793
794
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        if(segue.identifier == "toDetailView") {
795
796
797
            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
798
799
800
            let destDelegate = DeckTransitioningDelegate()
            destination.transitioningDelegate = destDelegate
            let tapped = sender as! FacilityCollectionViewCell //this is probably a bad idea just FYI future me
801
			destChild.facility = tapped.facility
Zach Knox's avatar
Zach Knox committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818

            // 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.
    }
819
	
820
821
822
823
	// MARK: - Peek and Pop
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
		guard let indexPath = LocationsList?.indexPathForItem(at: location) else { return nil }
Zach Knox's avatar
Zach Knox committed
824
825
826
827
828
829
830
831
832
833
834
835
		if(indexPath.section == 1 || currentAlerts.count == 0) {
			let cell = LocationsList?.cellForItem(at: indexPath) as? FacilityCollectionViewCell
			guard let detailView = storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController else { return nil }
			detailView.facility = cell?.facility
			return detailView
		}
		else {
			let cell = LocationsList?.cellForItem(at: indexPath) as? AlertCollectionViewCell
			guard let detailView = storyboard?.instantiateViewController(withIdentifier: "alertDetail") as? AlertDetailViewController else { return nil }
			detailView.alert = cell?.alert
			return detailView
		}
Zach Knox's avatar
Zach Knox committed
836

837
838
839
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
840
841
		let finalDestination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController // Fox only, no items
		finalDestination?.currentViewController = viewControllerToCommit
Zach Knox's avatar
Zach Knox committed
842
		let destDelegate = DeckTransitioningDelegate()
843
844
		finalDestination?.modalPresentationStyle = .custom
		finalDestination?.transitioningDelegate = destDelegate
Zach Knox's avatar
Zach Knox committed
845
		//If one day 3D touch comes to the iPad, this is no longer good.
846
		present(finalDestination!, animated: true, completion: nil)
847
848
	}
	
849
}
Zac Wood's avatar
Zac Wood committed
850
851
852
853
854

// 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
855
        shownFacilities = filterFacilitiesForSearchText(searchText)
Zac Wood's avatar
Zac Wood committed
856
857
858
    }
}

Zach Knox's avatar
Zach Knox committed
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
// 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
901
902