FacilitiesListViewController.swift 33.2 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
import StoreKit
13

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


23
class FacilitiesListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIViewControllerPreviewingDelegate, UICollectionViewDelegateFlowLayout {
24

25
26
27
28
	// 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).
29
30
31
32
33
		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
34

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

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

61
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
62
	
63
	@IBOutlet var favoritesControl: UISegmentedControl!
Zach Knox's avatar
Zach Knox committed
64
	var showFavorites = false
65
66
    
    let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
67

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

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

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

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

Zach Knox's avatar
Zach Knox committed
181
182
	}
	
183
	var goodToGo = false
Zach Knox's avatar
Zach Knox committed
184
	@objc func toDetailFromSearch(_ notification: Notification) {
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
		func toDetailCompletion() {
			let dest = self.storyboard?.instantiateViewController(withIdentifier: "detailView") as! FacilityDetailViewController
			let userActivity = notification.object as? NSUserActivity
			if(userActivity == nil) {
				return // don't do anything
			}
			let facility = realm.objects(FacilitiesModel.self)[0].facilities.filter(NSPredicate(format: "facilityName = '" + (userActivity?.title)! + "'")).first
			if(facility == nil) {
				return // don't do anything
			}
			dest.facility = facility!
			
			let detailViewWithButtons = self.storyboard?.instantiateViewController(withIdentifier: "detailViewButtons") as? DetailViewButtonsViewController
			detailViewWithButtons?.detailViewController = dest
			detailViewWithButtons?.facility = dest.facility
			let buttonDest = detailViewWithButtons!
			
			let finalDestination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController // Fox only, no items
			finalDestination?.currentViewController = buttonDest
			let destDelegate = DeckTransitioningDelegate(isSwipeToDismissEnabled: true, dismissCompletion: begForReviews)
			finalDestination?.modalPresentationStyle = .custom
			finalDestination?.transitioningDelegate = destDelegate
			
			// present the detail view over the search controller if we're searching
			if searchController.isActive {
				searchController.present(finalDestination!, animated: true, completion: nil)
			}
			else {
				present(finalDestination!, animated: true, completion: nil)
			}
215
		}
Zach Knox's avatar
Zach Knox committed
216
		
217
218
219
220
221
		if(goodToGo) {
			toDetailCompletion()
		} else {
			sleep(1)
			update(notification, completion: toDetailCompletion)
Zach Knox's avatar
Zach Knox committed
222
223
		}
	}
224
	func presentDetailView(_ destination: UIViewController, tapped: UICollectionViewCell) {
225
226
227
228
229
230
231
232
233
234
		var trueDest: UIViewController
		if destination is FacilityDetailViewController {
			let detailViewWithButtons = self.storyboard?.instantiateViewController(withIdentifier: "detailViewButtons") as? DetailViewButtonsViewController
			detailViewWithButtons?.detailViewController = (destination as! FacilityDetailViewController)
			detailViewWithButtons?.facility = (destination as! FacilityDetailViewController).facility
			trueDest = detailViewWithButtons!
		}
		else {
			trueDest = destination
		}
Zach Knox's avatar
Zach Knox committed
235
236
237
		if(self.view.traitCollection.horizontalSizeClass == .regular && self.view.traitCollection.verticalSizeClass == .regular) {
			//do a popover here for the iPad
			//iPads are cool right?
238
239
			trueDest.modalPresentationStyle = .popover
			let popoverController = trueDest.popoverPresentationController
Zach Knox's avatar
Zach Knox committed
240
			popoverController?.permittedArrowDirections = .any
241
242
			popoverController?.sourceView = tapped.contentView
			popoverController?.sourceRect = tapped.bounds
Zac Wood's avatar
Zac Wood committed
243
244
245
            
            // present the detail view over the search controller if we're searching
            if searchController.isActive {
246
                searchController.present(trueDest, animated: true, completion: nil)
Zac Wood's avatar
Zac Wood committed
247
248
            }
            else {
249
                present(trueDest, animated: true, completion: nil)
Zac Wood's avatar
Zac Wood committed
250
            }
Zach Knox's avatar
Zach Knox committed
251
252
		}
		else {
253
			let finalDestination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController // Fox only, no items
254
			finalDestination?.currentViewController = trueDest
255
			let destDelegate = DeckTransitioningDelegate(isSwipeToDismissEnabled: true, dismissCompletion: begForReviews)
256
257
			finalDestination?.modalPresentationStyle = .custom
			finalDestination?.transitioningDelegate = destDelegate
Zac Wood's avatar
Zac Wood committed
258
259
260
            
            // present the detail view over the search controller if we're searching
            if searchController.isActive {
261
				searchController.present(finalDestination!, animated: true, completion: nil)
Zac Wood's avatar
Zac Wood committed
262
263
            }
            else {
264
				present(finalDestination!, animated: true, completion: nil)
Zac Wood's avatar
Zac Wood committed
265
            }
Zach Knox's avatar
Zach Knox committed
266
		}
Zac Wood's avatar
Zac Wood committed
267
268
        
        
Zach Knox's avatar
Zach Knox committed
269
	}
270
271
272
273
274
275
276
277
278
279
280
281
	
	func begForReviews(_ dismissed: Bool) {
		// MARK - Begging for App Reviews
		let prompt = UserDefaults.standard.integer(forKey: "reviewPrompt")
		if(arc4random_uniform(100) > 92 && prompt >= 4) {
			SKStoreReviewController.requestReview()
			UserDefaults.standard.set(0, forKey: "reviewPrompt")
		}
		else {
			UserDefaults.standard.set(prompt + 1, forKey: "reviewPrompt")
		}
	}
Zac Wood's avatar
Zac Wood committed
282
283
284
285
286
287
288
289
290
    
    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
291
292
	
	override func viewDidLoad() {
Zach Knox's avatar
Zach Knox committed
293
294
		NotificationCenter.default.addObserver(self, selector: #selector(toDetailFromSearch(_:)), name: NSNotification.Name(rawValue: "launchToFacility"), object: nil)
		
295
        super.viewDidLoad()
Zach Knox's avatar
Zach Knox committed
296
297
		let nc = NotificationCenter.default
		nc.addObserver(self, selector: #selector(anyRefresh(_:)), name: .UIApplicationWillEnterForeground, object: nil)
298
		
299
		self.definesPresentationContext = true
Zac Wood's avatar
Zac Wood committed
300
        
Zach Knox's avatar
Zach Knox committed
301
        navigationItem.title = "What's Open"
302
		navigationController?.navigationBar.prefersLargeTitles = true
303
304
		navigationItem.largeTitleDisplayMode = .always
		
Zac Wood's avatar
Zac Wood committed
305
        configureSearchController()
Zach Knox's avatar
Zach Knox committed
306
		
307
		LocationsListLayout.invalidateLayout()
Zach Knox's avatar
Zach Knox committed
308
		
309
310
		settingsButton.accessibilityLabel = "Settings"
		
311
		LocationsListLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
Zach Knox's avatar
Zach Knox committed
312

Zach Knox's avatar
Zach Knox committed
313
		refreshControl.addTarget(self, action: #selector(forceRefresh(_:)), for: .valueChanged)
314
		LocationsList.refreshControl = refreshControl
Zach Knox's avatar
Zach Knox committed
315
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
316

317
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
318
		refresh(self, forceUpdate: false)
Zach Knox's avatar
Zach Knox committed
319
		
320
		reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
321
		
322
	}
Zach Knox's avatar
Zach Knox committed
323
	
324
	func reloadWithFilters() {
Zach Knox's avatar
Zach Knox committed
325
326
		
		// Facilities
327
		filteredFacilities = filters.applyFiltersOnFacilities(facilitiesArray)
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

		
		let defaults = UserDefaults.standard

		
		// Campuses
		// By the time you've called reloadWithFilters(), the defaults list should already be updated to include
		// all campuses via updateFilterLists
		let campusFilters = defaults.dictionary(forKey: "campuses") as! [String: Bool]?
		
		let filteredByCampus = List<Facility>()
		for facility in filteredFacilities {
			if campusFilters![(facility.facilityLocation?.campus.lowercased())!]! {
				filteredByCampus.append(facility)
			}
		}
		filteredFacilities = filteredByCampus
		
346
347
		shownFacilities = filteredFacilities
		favoritesControlChanges(self)
Zach Knox's avatar
Zach Knox committed
348
349
350
351
352
353
		
		// Alerts
		let shown = List<Alert>()
		let formatter = ISO8601DateFormatter()
		formatter.timeZone = TimeZone(identifier: "America/New_York")
		let now = Date()
354
		let alertFilers = defaults.dictionary(forKey: "alerts") as! [String: Bool]?
Zach Knox's avatar
Zach Knox committed
355
356
		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
357
358
				switch alert.urgency {
				case "info":
Zach Knox's avatar
Zach Knox committed
359
					if(alertFilers!["informational"])! {
Zach Knox's avatar
Zach Knox committed
360
361
362
						shown.append(alert)
					}
				case "minor":
Zach Knox's avatar
Zach Knox committed
363
					if(alertFilers!["minor alerts"])! {
Zach Knox's avatar
Zach Knox committed
364
365
366
						shown.append(alert)
					}
				case "major":
Zach Knox's avatar
Zach Knox committed
367
					if(alertFilers!["major alerts"])! {
Zach Knox's avatar
Zach Knox committed
368
369
370
371
372
						shown.append(alert)
					}
				default:
					shown.append(alert)
				}
Zach Knox's avatar
Zach Knox committed
373
374
375
376
377
			}
		}
		currentAlerts = shown
		
		
378
379
		LocationsList.reloadData()
	}
Zac Wood's avatar
Zac Wood committed
380
381
382
383
384
385
386
387
388
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
389
390
391
392
393
394
395
396
397
398
    /**
     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>
399
400
		
		/*
401
402
403
404
405
406
407
408
409
410
411
412
413
414
        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
                })
            }
415

416
        } else {
417
418
419
420
421
422
423
424
425
		  */
		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
426
            let hasAbbreviation = facility.facilityLocation?.abbreviation.lowercased().contains(searchText.lowercased()) ?? false
427
			let hasCategory = facility.category?.categoryName.lowercased().contains(searchText.lowercased()) ?? false
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
			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
446
			return hasName || hasBuilding || hasCategory || hasTag || hasAbbreviation
447
		})
448
        
Zac Wood's avatar
Zac Wood committed
449
        LocationsList.reloadData()
450
        return filtered
Zac Wood's avatar
Zac Wood committed
451
    }
Zach Knox's avatar
Zach Knox committed
452
	
Zach Knox's avatar
Zach Knox committed
453
454
455
456
457
458
459
460
	
	// These functions are for use by selectors
	@objc private func forceRefresh(_ sender: Any) {
		refresh(sender, forceUpdate: true)
	}
	@objc private func anyRefresh(_ sender: Any) {
		refresh(sender, forceUpdate: false)
	}
461
462
463
464
	/*
	* Reloads data, either calling update() to attempt a download
	* or simply pulling from the realm
	*/
465
	@objc func refresh(_ sender: Any, forceUpdate: Bool = true) {
Zach Knox's avatar
Zach Knox committed
466
		refreshControl.beginRefreshing()
Zach Knox's avatar
Zach Knox committed
467
468
469
470
471
472
473
474
		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
475
				let alerts = model.alerts
Zach Knox's avatar
Zach Knox committed
476
477
				let lastUpdated = model.lastUpdated
				
478
479
				if((facilities.isEmpty && alerts.isEmpty) || lastUpdated.isLessThanDate(dateToCompare:
				  	Date(timeIntervalSinceNow: -43200.0))) {
Zach Knox's avatar
Zach Knox committed
480
481
482
483
					update(sender)
				}
				else {
					facilitiesArray = facilities
Zach Knox's avatar
Zach Knox committed
484
					alertsList = alerts
485
					self.refreshControl.attributedTitle = NSAttributedString(string: "Last Updated: " + self.shortDateFormat(lastUpdated))
486
				  	goodToGo = true
Zach Knox's avatar
Zach Knox committed
487
488
489
490
491
492
493
				}
			}
			else {
				update(sender)
			}

		}
Zac Wood's avatar
Zac Wood committed
494
				
495
		updateFiltersLists()
496
		checkFilterState()
497
		reloadWithFilters()
Zac Wood's avatar
Zac Wood committed
498
        
499
500
501
502
		refreshControl.endRefreshing()
	}
	
	func updateFiltersLists() {
503
		// Add locations and categories to filters
504
505
		let defaults = UserDefaults.standard
		var campusFilters = defaults.dictionary(forKey: "campuses") as! [String: Bool]?
506
507
		for f in facilitiesArray {
			if(!filters.onlyFromCategories.keys.contains((f.category?.categoryName)!)) {
508
				filters.onlyFromCategories.updateValue(true, forKey: (f.category?.categoryName)!.lowercased())
509
510
			}
			if(!filters.onlyFromLocations.keys.contains((f.facilityLocation?.building)!)) {
511
				filters.onlyFromLocations.updateValue(true, forKey: (f.facilityLocation?.building)!.lowercased())
512
			}
513
514
			if(!campusFilters!.keys.contains((f.facilityLocation?.campus)!)) {
				campusFilters!.updateValue(true, forKey: (f.facilityLocation?.campus)!.lowercased())
515
			}
516
		}
517
		defaults.set(campusFilters, forKey: "campuses")
Zach Knox's avatar
Zach Knox committed
518
	}
Zach Knox's avatar
Zach Knox committed
519
	
520
521
522
523
	/*
	* Attempts to update facilitiesArray from the network
	* and place that new information into Realm
	*/
524
	func update(_ sender: Any, completion: (() -> ())? = nil) {
Zach Knox's avatar
Zach Knox committed
525
		DownloadController.performDownload { (facilities) in
Zach Knox's avatar
Zach Knox committed
526
527
528
529
530
531
532
533
534
			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
535
						self.updateFiltersLists()
536
						self.reloadWithFilters()
537
538
						self.refreshControl.attributedTitle = NSAttributedString(string: "Last Updated: " + self.shortDateFormat(lastUpdated))
						self.refreshControl.endRefreshing()
539
540
541
542
						self.goodToGo = true
						if(completion != nil) {
							completion!()
						}
Zach Knox's avatar
Zach Knox committed
543
544
545
					}
					else {
						self.facilitiesArray = List<Facility>()
Zach Knox's avatar
Zach Knox committed
546
547
					}
				}
Zach Knox's avatar
Zach Knox committed
548
549
550
551
552
553
			}
			else {
				self.facilitiesArray = facilities!
				
				DispatchQueue.main.async {
					let date = Date()
554
					self.refreshControl.attributedTitle = NSAttributedString(string: "Last Updated: " + self.shortDateFormat(date))
Zach Knox's avatar
Zach Knox committed
555

Zach Knox's avatar
Zach Knox committed
556
557
					let results = self.realm.objects(FacilitiesModel.self)
					if results.count == 0 {
Zach Knox's avatar
Zach Knox committed
558
559
560
561
562
						let model = FacilitiesModel()
						for f in facilities! {
							model.facilities.append(f)
						}
						model.lastUpdated = date
Zach Knox's avatar
Zach Knox committed
563
564
565
						try! self.realm.write {
							self.realm.add(model)
						}
566
567
568
569
						self.goodToGo = true
						if(completion != nil) {
							completion!()
						}
Zach Knox's avatar
Zach Knox committed
570
571
572
573
					}
					else {
						let fromRealm = results[0]
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
574
575
576
577
578
							fromRealm.facilities.removeAll()
							for f in facilities! {
								fromRealm.facilities.append(f)
							}
							fromRealm.lastUpdated = date
Zach Knox's avatar
Zach Knox committed
579
						}
Zach Knox's avatar
Zach Knox committed
580
					}
581
582
					self.updateFiltersLists()
					self.reloadWithFilters()
583
					self.refreshControl.endRefreshing()
584
585
586
587
					self.goodToGo = true
					if(completion != nil) {
						completion!()
					}
Zach Knox's avatar
Zach Knox committed
588
				}
Zach Knox's avatar
Zach Knox committed
589
			}
Zach Knox's avatar
Zach Knox committed
590
		}
Zach Knox's avatar
Zach Knox committed
591
		DownloadController.performAlertsDownload { (alerts) in
Zach Knox's avatar
Zach Knox committed
592
593
594
595
596
			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
597
						self.alertsList = model.alerts
Zach Knox's avatar
Zach Knox committed
598
599
600
601
602
603
604
605
606
607
608
609
610
					}
					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
611
612
613
614
							let model = FacilitiesModel()
							for a in alerts! {
								model.alerts.append(a)
							}
Zach Knox's avatar
Zach Knox committed
615
616
617
618
619
620
							self.realm.add(model)
						}
					}
					else {
						let fromRealm = results[0]
						try! self.realm.write {
Zach Knox's avatar
Zach Knox committed
621
622
623
624
							fromRealm.alerts.removeAll()
							for a in alerts! {
								fromRealm.alerts.append(a)
							}
Zach Knox's avatar
Zach Knox committed
625
626
						}
					}
627
					self.reloadWithFilters()
Zach Knox's avatar
Zach Knox committed
628
629
				}
			}
630
		}
Zach Knox's avatar
Zach Knox committed
631
	}
Zac Wood's avatar
Zac Wood committed
632
    
633
634
635
636
637
638
639
640
641
	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
642
	
643
644
645
646
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
Zach Knox's avatar
Zach Knox committed
647

648
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
649
		if currentAlerts.count > 0 {
Zach Knox's avatar
Zach Knox committed
650
651
652
653
654
			return 2
		}
		else {
			return 1
		}
655
	}
Zach Knox's avatar
Zach Knox committed
656

657
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
Zach Knox's avatar
Zach Knox committed
658
		if(section == 1 || currentAlerts.count == 0) {
Zach Knox's avatar
Zach Knox committed
659
660
661
662
			return shownFacilities.count
		}
		else {
			// TODO: get current alerts, not just any alerts
Zach Knox's avatar
Zach Knox committed
663
			return currentAlerts.count
Zach Knox's avatar
Zach Knox committed
664
665
		}
		
666
	}
Zach Knox's avatar
Zach Knox committed
667

668
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
Zach Knox's avatar
Zach Knox committed
669
		
Zach Knox's avatar
Zach Knox committed
670
		if (indexPath.section == 1 || currentAlerts.count == 0) {
Zach Knox's avatar
Zach Knox committed
671
672
673
674
675
			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
676
			cell.frame.size.width = 280
Zach Knox's avatar
Zach Knox committed
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
			}
			*/
			//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
704
705
706
707
708
709
			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
710
711
712
713
			cell.categoryLabel.text = facility.category?.categoryName.uppercased()
			
			cell.openClosedLabel.text = Utilities.openOrClosedUntil(facility)
			
Zach Knox's avatar
Zach Knox committed
714
			// TODO: Change the name of this label
Zach Knox's avatar
Zach Knox committed
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
			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
730
				cell.backgroundColor = UIColor(red:0.17, green:0.17, blue: 0.17, alpha: 1.0)
Zach Knox's avatar
Zach Knox committed
731
732
733
734
				
			}
			
			//Accessibility
735
			cell.accessibilityLabel = cell.nameLabel.text! + " " + cell.categoryLabel.text! + ", Currently " + cell.openClosedLabel.text! + ". Located in" + cell.timeDescriptionLabel.text!
Zach Knox's avatar
Zach Knox committed
736
737
738
			cell.accessibilityHint = "Double Tap to view details"
			
			
739
740
741
742
743
744
745
			//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
746
			self.reloadInputViews()
747
748
749
750
			
			if(traitCollection.forceTouchCapability == .available) {
				self.registerForPreviewing(with: self, sourceView: cell)
			}
Zach Knox's avatar
Zach Knox committed
751
			return cell
Zach Knox's avatar
Zach Knox committed
752
		}
Zach Knox's avatar
Zach Knox committed
753
754
		else {
			// Do Alerts things here
Zach Knox's avatar
Zach Knox committed
755
			let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Alert Cell", for: indexPath) as! AlertCollectionViewCell
756
			cell.viewWidth = self.view.frame.width
757
758
759
760
			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
761
			
Zach Knox's avatar
Zach Knox committed
762
763
764
			switch currentAlerts[indexPath.row].urgency {
			case "info":
				cell.imageView.image = #imageLiteral(resourceName: "info")
765
				cell.imageView.accessibilityLabel = "Info"
Zach Knox's avatar
Zach Knox committed
766
767
			case "minor":
				cell.imageView.image = #imageLiteral(resourceName: "minor")
768
				cell.imageView.accessibilityLabel = "Minor Alert"
Zach Knox's avatar
Zach Knox committed
769
770
			case "major":
				cell.imageView.image = #imageLiteral(resourceName: "major")
771
				cell.imageView.accessibilityLabel = "Major Alert"
Zach Knox's avatar
Zach Knox committed
772
773
			case "emergency":
				cell.imageView.image = #imageLiteral(resourceName: "emergency")
774
				cell.imageView.accessibilityLabel = "Emergency Alert"
Zach Knox's avatar
Zach Knox committed
775
776
			default:
				cell.imageView.image = #imageLiteral(resourceName: "major")
777
				cell.imageView.accessibilityLabel = "Alert"
Zach Knox's avatar
Zach Knox committed
778
			}
Zach Knox's avatar
Zach Knox committed
779
			cell.messageLabel.text = currentAlerts[indexPath.row].message
780

781
782
783
			if(traitCollection.forceTouchCapability == .available) {
				self.registerForPreviewing(with: self, sourceView: cell)
			}
Zach Knox's avatar
Zach Knox committed
784
			return cell
785
		}
Zach Knox's avatar
Zach Knox committed
786

787
	}
788
	
789
	// MARK - Collection View Cell Layout
790
	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
Zach Knox's avatar
Zach Knox committed
791
		if(indexPath.section == 1 || currentAlerts.count == 0) {
792
793
794
			let height = LocationsListLayout.itemSize.height
			let width: CGFloat
			
795
796
			let edgeInsets = self.view.safeAreaInsets
			let windowWidth = self.view.frame.size.width - edgeInsets.left - edgeInsets.right
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
			
			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 {
814
815
			let edgeInsets = self.view.safeAreaInsets
			return CGSize(width: self.view.frame.size.width - edgeInsets.left - edgeInsets.right, height: 43)
816
817
		}
	}
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
	
	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
		}
	}
836
837
838

	func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
		var sectionInsets = LocationsListLayout.sectionInset
Zach Knox's avatar
Zach Knox committed
839
		if(section != 1 && currentAlerts.count != 0) {
840
841
			sectionInsets.top = 0
		}
Zach Knox's avatar
Zach Knox committed
842
843
844
		else if currentAlerts.count == 0 {
			sectionInsets.top = 15
		}
845
846
		return sectionInsets
	}
Zach Knox's avatar
Zach Knox committed
847

848
849
	
	//unused
Zach Knox's avatar
Zach Knox committed
850
	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
851
852
853
854
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
855
			return placeOpenFacilitiesFirstInArray(filteredFacilities)
Zach Knox's avatar
Zach Knox committed
856
		}
Zach Knox's avatar
Zach Knox committed
857
858


Zach Knox's avatar
Zach Knox committed
859
	}
860
	
861
	//unused
Zac Wood's avatar
Zac Wood committed
862
863
864
	// 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
865
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
866
867
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
868

869
870
871
872
873
874
875
876
877
878
879
		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
880

881
	//unused
882
883
884
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
885

886
887
888
889
890
891
892
893
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
894

895
896
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
897
898


899
900
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
901
	//unused
Zach Knox's avatar
Zach Knox committed
902
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zach Knox's avatar
Zach Knox committed
903
904
905
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        if(segue.identifier == "toDetailView") {
906
907
908
            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
909
910
911
            let destDelegate = DeckTransitioningDelegate()
            destination.transitioningDelegate = destDelegate
            let tapped = sender as! FacilityCollectionViewCell //this is probably a bad idea just FYI future me
912
			destChild.facility = tapped.facility
Zach Knox's avatar
Zach Knox committed
913
914
915
916
917
918
919
920
921
922
923
924
925

            // 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
Zac Wood's avatar
Zac Wood committed
926
927
928
            filterView.updateFacilities = { [weak self] in
                self?.reloadWithFilters()
            }
Zach Knox's avatar
Zach Knox committed
929
930
931
932
        }

        // Pass the selected object to the new view controller.
    }
933
	
934
935
936
937
	// 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
938
939
		if(indexPath.section == 1 || currentAlerts.count == 0) {
			let cell = LocationsList?.cellForItem(at: indexPath) as? FacilityCollectionViewCell
940
			previewingContext.sourceRect = (cell?.bounds)!
Zach Knox's avatar
Zach Knox committed
941
942
943
944
945
946
947
948
949
950
			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
951

952
953
954
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
955
956
957
958
959
960
961
962
963
964
965
966
967
968
		guard let facilityDetailView = viewControllerToCommit as? FacilityDetailViewController
			else {
				let finalDestination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController // Fox only, no items
				finalDestination?.currentViewController = viewControllerToCommit
				let destDelegate = DeckTransitioningDelegate()
				finalDestination?.modalPresentationStyle = .custom
				finalDestination?.transitioningDelegate = destDelegate
				//If one day 3D touch comes to the iPad, this is no longer good.
				present(finalDestination!, animated: true, completion: nil)
				return
			}
	  	let detailViewWithButtons = self.storyboard?.instantiateViewController(withIdentifier: "detailViewButtons") as? DetailViewButtonsViewController
		detailViewWithButtons?.detailViewController = facilityDetailView
		detailViewWithButtons?.facility = facilityDetailView.facility
969
		let finalDestination = self.storyboard?.instantiateViewController(withIdentifier: "pulling") as? PullingViewController // Fox only, no items
970
		finalDestination?.currentViewController = detailViewWithButtons
Zach Knox's avatar
Zach Knox committed
971
		let destDelegate = DeckTransitioningDelegate()
972
973
		finalDestination?.modalPresentationStyle = .custom
		finalDestination?.transitioningDelegate = destDelegate
Zach Knox's avatar
Zach Knox committed
974
		//If one day 3D touch comes to the iPad, this is no longer good.
975
		present(finalDestination!, animated: true, completion: nil)
976

977
978
	}
	
979
}
Zac Wood's avatar
Zac Wood committed
980
981
982
983
984

// 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
985
        shownFacilities = filterFacilitiesForSearchText(searchText)
Zac Wood's avatar
Zac Wood committed
986
987
988
    }
}

Zach Knox's avatar
Zach Knox committed
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
// 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
1031
1032