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

13
class FacilitiesListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIViewControllerPreviewingDelegate {
14

Zach Knox's avatar
Zach Knox committed
15
	var facilitiesArray = List<Facility>()
Zac Wood's avatar
Zac Wood committed
16
17
18
19
20
    var filteredFacilities = List<Facility>()
    
    // passing in nil sets the controller to be this controller
    let searchController = UISearchController(searchResultsController: nil)

Zach Knox's avatar
Zach Knox committed
21
	var filters = Filters()
22
	
23
24
25
26
	override var preferredStatusBarStyle: UIStatusBarStyle {
		return .default
	}
	
27
	@IBOutlet var LeftButton: UIBarButtonItem!
Zach Knox's avatar
Zach Knox committed
28

29
30
31
32
	@IBAction func RightButton(_ sender: Any) {
	}
	@IBOutlet var RightButton: UIBarButtonItem!
	
33
34
	@IBOutlet var settingsButton: UIBarButtonItem!
	
35
	@IBOutlet var LocationsList: UICollectionView!
Zach Knox's avatar
Zach Knox committed
36

37
	@IBOutlet var LocationsListLayout: UICollectionViewFlowLayout!
Zach Knox's avatar
Zach Knox committed
38

39
	@IBOutlet var favoritesControl: UISegmentedControl!
Zach Knox's avatar
Zach Knox committed
40
41
	var showFavorites = false

42
	@IBOutlet var LastUpdatedLabel: UIBarButtonItem!
Zach Knox's avatar
Zach Knox committed
43

Zach Knox's avatar
Zach Knox committed
44
45
46
47
48
49
50
51
52
53
54
55
	@IBAction func favoritesControlChanges(_ sender: Any) {
		switch (self.favoritesControl.selectedSegmentIndex)
		{
		case 0:
			showFavorites = false
		case 1:
			showFavorites = true
		default:
			showFavorites = false
		}
		self.LocationsList.reloadData()
	}
Zach Knox's avatar
Zach Knox committed
56

Zach Knox's avatar
Zach Knox committed
57
	let refreshControl = UIRefreshControl()
Zach Knox's avatar
Zach Knox committed
58

59
	override func viewWillLayoutSubviews() {
Zach Knox's avatar
Zach Knox committed
60
61
62
63
64
65
		LocationsListLayout.itemSize.width = getCellWidth()
		LocationsListLayout.invalidateLayout()

	}
	
	func getCellWidth() -> CGFloat {
66
67
		let windowWidth = self.view.frame.size.width
		
Zach Knox's avatar
Zach Knox committed
68
69
		if(windowWidth < 640) {
			return windowWidth - 20
70
71
		}
		else if(windowWidth >= 640 && windowWidth < 1024) {
Zach Knox's avatar
Zach Knox committed
72
			return (windowWidth / 2) - 15
73
74
		}
		else if(windowWidth >= 1024) {
Zach Knox's avatar
Zach Knox committed
75
			return (windowWidth / 3) - 15
76
77
		}
		
Zach Knox's avatar
Zach Knox committed
78
		return 0
79
	}
Zach Knox's avatar
Zach Knox committed
80

81
82
83
	@IBAction func RefreshButton(_ sender: Any) {
		refresh(sender)
	}
Zach Knox's avatar
Zach Knox committed
84

85
86
87
88
	override func viewWillAppear(_ animated: Bool) {
		LastUpdatedLabel.isEnabled = false
	}
	
Zach Knox's avatar
Zach Knox committed
89
	@objc func tapRecognizer(_ sender: UITapGestureRecognizer) {
Zach Knox's avatar
Zach Knox committed
90
91
92
		
		let tapLocation = sender.location(in: LocationsList)
		let indexPath = LocationsList.indexPathForItem(at: tapLocation)
Zac Wood's avatar
Zac Wood committed
93
        
Zach Knox's avatar
Zach Knox committed
94
		if((indexPath) != nil) {
Zac Wood's avatar
Zac Wood committed
95
96
97
98
99
            let destination = self.storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController
            let tapped = self.LocationsList.cellForItem(at: indexPath!) as! FacilityCollectionViewCell
            destination!.facility = tapped.facility
            self.presentDetailView(destination!)
            
Zach Knox's avatar
Zach Knox committed
100
101
102
103
104
105
106
		}
	}
	
	func presentDetailView(_ destination: FacilityDetailViewController) {
		if(self.view.traitCollection.horizontalSizeClass == .regular && self.view.traitCollection.verticalSizeClass == .regular) {
			//do a popover here for the iPad
			//iPads are cool right?
Zach Knox's avatar
Zach Knox committed
107
108
109
110
			destination.modalPresentationStyle = .popover
			let popoverController = destination.popoverPresentationController
			popoverController?.permittedArrowDirections = .any
			popoverController?.sourceView = destination.view
Zac Wood's avatar
Zac Wood committed
111
112
113
114
115
116
117
118
            
            // 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
119
120
121
122
123
		}
		else {
			let destDelegate = DeckTransitioningDelegate()
			destination.modalPresentationStyle = .custom
			destination.transitioningDelegate = destDelegate
Zac Wood's avatar
Zac Wood committed
124
125
126
127
128
129
130
131
            
            // 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
132
		}
Zac Wood's avatar
Zac Wood committed
133
134
        
        
Zach Knox's avatar
Zach Knox committed
135
	}
Zac Wood's avatar
Zac Wood committed
136
137
138
139
140
141
142
143
144
    
    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
145
146
	
	override func viewDidLoad() {
147
148
        super.viewDidLoad()
		
149
150
		self.definesPresentationContext = true
		
Zach Knox's avatar
Zach Knox committed
151
		if(traitCollection.forceTouchCapability == .available) {
152
153
			registerForPreviewing(with: self, sourceView: self.LocationsList!)
		}
Zach Knox's avatar
Zach Knox committed
154
155
        
        navigationItem.title = "What's Open"
156
		navigationController?.navigationBar.prefersLargeTitles = true
Zach Knox's avatar
Zach Knox committed
157
        
Zac Wood's avatar
Zac Wood committed
158
        configureSearchController()
Zach Knox's avatar
Zach Knox committed
159
		
160
		LocationsListLayout.invalidateLayout()
Zach Knox's avatar
Zach Knox committed
161
		
162
163
164
		settingsButton.accessibilityLabel = "Settings"
		LastUpdatedLabel.accessibilityHint = ""
		
165
		LocationsListLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
Zach Knox's avatar
Zach Knox committed
166

Zach Knox's avatar
Zach Knox committed
167
168
169
		refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
		LocationsList.addSubview(refreshControl)
		LocationsList.alwaysBounceVertical = true
Zach Knox's avatar
Zach Knox committed
170

171
		SRCTNetworkController.performDownload { (facilities) in
Zach Knox's avatar
Zach Knox committed
172
			self.facilitiesArray = List(facilities)
173
174
			DispatchQueue.main.async {
				self.LocationsList.reloadData()
175
176
				let date = Date()
				self.LastUpdatedLabel.title = "Updated: " + self.shortDateFormat(date)
177
178
			}
		}
179
180
		
	}
Zac Wood's avatar
Zac Wood committed
181
182
183
184
185
186
187
188
189
190
191
    
    func isSearchBarEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
    
    func isSearching() -> Bool {
        return searchController.isActive && !isSearchBarEmpty()
    }
    
    func filterFacilitiesForSearchText(_ searchText: String) {
        filteredFacilities = facilitiesArray.filter({(facility: Facility) -> Bool in
Zac Wood's avatar
Zac Wood committed
192
193
            let hasName = facility.facilityName.lowercased().contains(searchText.lowercased())
            let hasBuilding = facility.facilityLocation?.building.lowercased().contains(searchText.lowercased()) ?? false
194
195
			let hasCategory = facility.category?.categoryName.lowercased().contains(searchText.lowercased()) ?? false
            return hasName || hasBuilding || hasCategory
Zac Wood's avatar
Zac Wood committed
196
197
198
        })
        LocationsList.reloadData()
    }
Zach Knox's avatar
Zach Knox committed
199
	
Zach Knox's avatar
Zach Knox committed
200
	@objc func refresh(_ sender: Any) {
Zach Knox's avatar
Zach Knox committed
201
202
		refreshControl.beginRefreshing()
		LocationsList.reloadData()
203
204
		let date = Date()
		LastUpdatedLabel.title = "Updated: " + shortDateFormat(date)
Zach Knox's avatar
Zach Knox committed
205
206
		refreshControl.endRefreshing()
	}
Zac Wood's avatar
Zac Wood committed
207
    
208
209
210
211
212
213
214
215
216
	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
217
	
218
219
220
221
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
Zach Knox's avatar
Zach Knox committed
222

223
	func numberOfSections(in collectionView: UICollectionView) -> Int {
Zach Knox's avatar
Zach Knox committed
224
		return 1
225
	}
Zach Knox's avatar
Zach Knox committed
226

227
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
Zac Wood's avatar
Zac Wood committed
228
        return isSearching() ? self.filteredFacilities.count : self.facilitiesArray.count
229
	}
Zach Knox's avatar
Zach Knox committed
230

231
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
232
		let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! FacilityCollectionViewCell
Zach Knox's avatar
Zach Knox committed
233
234
235
236
237
238
239
		/*
		let windowRect = self.view.window!.frame
		let windowWidth = windowRect.size.width
		if(windowWidth <= 320) {
			cell.frame.size.width = 280
		}
		*/
Zach Knox's avatar
Zach Knox committed
240
        //Get tap of the cell
241
		cell.tapRecognizer.addTarget(self, action: #selector(FacilitiesListViewController.tapRecognizer(_:)))
Zach Knox's avatar
Zach Knox committed
242
        cell.gestureRecognizers = []
243
		cell.gestureRecognizers?.append(cell.tapRecognizer)
Zach Knox's avatar
Zach Knox committed
244
        
Zac Wood's avatar
Zac Wood committed
245
246
247
248
249
250
251
252
253
254
255
256
257
        
        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() {
            dataArray = placeOpenFacilitiesFirstInArray(filteredFacilities)
        } else {
            dataArray = placeOpenFacilitiesFirstInArray(facilitiesArray)
        }
        
		facility = dataArray[indexPath.row]
        
258
		cell.facility = facility
Zach Knox's avatar
Zach Knox committed
259
260
        
        //set labels
Zach Knox's avatar
Zach Knox committed
261
		cell.nameLabel.text = facility.facilityName
262
        cell.categoryLabel.text = facility.category?.categoryName.uppercased()
Zach Knox's avatar
Zach Knox committed
263

Zach Knox's avatar
Zach Knox committed
264
265
266
267
268
269
        cell.openClosedLabel.text = Utilities.openOrClosedUntil(facility)
        
        cell.timeDescriptionLabel.text = facility.facilityLocation?.building

        //change appearence based on open state
        let open = Utilities.isOpen(facility: facility)
270
		if(open == true) {
271
			//cell.openClosedLabel.text = "Open"
272
273
274
			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)
275
			cell.backgroundColor = UIColor(red:0.00, green:0.40, blue:0.20, alpha:1.0)
276
		} else {
277
			//cell.openClosedLabel.text = "Closed"
278
279
280
			cell.openClosedLabel.textColor = UIColor.white
			cell.openClosedLabel.backgroundColor = UIColor.black
			//cell.openClosedLabel.backgroundColor = UIColor.red
281
282
			cell.backgroundColor = UIColor.red

283
		}
Zach Knox's avatar
Zach Knox committed
284

Zach Knox's avatar
Zach Knox committed
285
        //Accessibility
286
        //TODO: FIX THIS
287
288
289
290
		cell.accessibilityLabel = cell.nameLabel.text! + ", Currently " + cell.openClosedLabel.text! + "." + cell.timeDescriptionLabel.text!
		cell.accessibilityHint = "Double Tap to view details"

		
291
292
293
		self.reloadInputViews()
		return cell
	}
Zach Knox's avatar
Zach Knox committed
294
295

	func getLocationArray(_ facilitiesArray: List<Facility>) -> [Facility] {
Zach Knox's avatar
Zach Knox committed
296
297
298
299
300
301
		if(!showFavorites) {
			return placeOpenFacilitiesFirstInArray(facilitiesArray)
		}
		else {
			return [] //TODO - INCOMPLETE
		}
Zach Knox's avatar
Zach Knox committed
302
303


Zach Knox's avatar
Zach Knox committed
304
	}
Zach Knox's avatar
Zach Knox committed
305

Zac Wood's avatar
Zac Wood committed
306
307
308
	// 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
309
	func placeOpenFacilitiesFirstInArray(_ facilitiesArray: List<Facility>) -> [Facility] {
310
311
		var open = [Facility]()
		var closed = [Facility]()
Zach Knox's avatar
Zach Knox committed
312

313
314
315
316
317
318
319
320
321
322
323
		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
324

325
326
327
	func countForOpenAndClosedFacilities(_ facilitiesArray: Array<Facility>) -> (open: Int, closed: Int) {
		var open = 0
		var closed = 0
Zach Knox's avatar
Zach Knox committed
328

329
330
331
332
333
334
335
336
		for i in facilitiesArray {
			if(Utilities.isOpen(facility: i)) {
				open += 1
			}
			else {
				closed += 1
			}
		}
Zach Knox's avatar
Zach Knox committed
337

338
339
		return (open, closed)
	}
Zach Knox's avatar
Zach Knox committed
340
341


342
343
    // MARK: - Navigation

Zach Knox's avatar
Zach Knox committed
344
    //In a storyboard-based application, you will often want to do a little preparation before navigation
Zac Wood's avatar
Zac Wood committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        // Get the new view controller using segue.destinationViewController.
//        if(segue.identifier == "toDetailView") {
//            let destination = segue.destination as! FacilityDetailViewController
//            let destDelegate = DeckTransitioningDelegate()
//            destination.transitioningDelegate = destDelegate
//            let tapped = sender as! FacilityCollectionViewCell //this is probably a bad idea just FYI future me
//            destination.facility = tapped.facility
//
//            // if we're in the search view, present on its controller
//            if searchController.isActive {
//                searchController.present(destination, animated: true, completion: nil)
//            } else {
//                present(destination, animated: true, completion: nil)
//            }
//        }
//        else if(segue.identifier == "toFilters") {
//            let destination = segue.destination as! UINavigationController
//            let filterView = destination.topViewController as! FiltersTableViewController
//            filterView.filters = self.filters
//        }
//
//        // Pass the selected object to the new view controller.
//    }
369
	
370
371
372
373
	// MARK: - Peek and Pop
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
		guard let indexPath = LocationsList?.indexPathForItem(at: location) else { return nil }
374
375
		let cell = LocationsList?.cellForItem(at: indexPath) as! FacilityCollectionViewCell
		guard let detailView = storyboard?.instantiateViewController(withIdentifier: "detailView") as? FacilityDetailViewController else { return nil }
376
377
		
		detailView.facility = cell.facility
Zach Knox's avatar
Zach Knox committed
378

379
380
381
382
		return detailView
	}
	
	func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
Zach Knox's avatar
Zach Knox committed
383
384
385
386
387
		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)
388
389
	}
	
390
}
Zac Wood's avatar
Zac Wood committed
391
392
393
394
395
396
397
398
399

// 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 ?? ""
        filterFacilitiesForSearchText(searchText)
    }
}