Files
eqn.ios/Sources/Earthquake Network/Controllers/Seismic Networks/SeismicNetworksViewController.swift
T
2020-09-26 14:08:23 +02:00

220 lines
7.6 KiB
Swift

//
// SeismicNetworksViewController.swift
// Earthquake Network
//
// Created by Busi Andrea on 22/09/2020.
// Copyright © 2020 Earthquake Network. All rights reserved.
//
import UIKit
import EventKitUI
class SeismicNetworksViewController: EQNBaseViewController, UITableViewDelegate, UITableViewDataSource {
private static let SegueIdentifierFilters = "FiltriEntiSismici"
private static let SegueIdentifierSettings = "impostazioniEntiSismi"
private static let SegueIdentifierSeismicNetworks = "elencoRetiSismiche"
// MARK: - Internal
@IBOutlet private weak var tableView: UITableView?
private var seismics = [EQNSisma]()
/// Index path of row with map expanded
private var openMapIndexPath: IndexPath?
/// Index path of row with weather expanded
private var openWeatherIndexPath: IndexPath?
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(didReceiveDownloadCompletedNotification(_:)),
name: NSNotification.Name(rawValue: NOTIFICA_DOWNLOAD_TERMINATO),
object: nil)
setupUI()
refreshUI()
}
private func setupUI() {
title = NSLocalizedString("tab_official", comment: "")
tableView?.estimatedRowHeight = 300.0;
tableView?.rowHeight = UITableView.automaticDimension
tableView?.register(SeismicNetworkTableViewCell.self, forCellReuseIdentifier: SeismicNetworkTableViewCell.Identifier)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// todo
}
// MARK: - Notification
@objc func didReceiveDownloadCompletedNotification(_ notification: NSNotification) {
DispatchQueue.main.async {
self.refreshUI()
}
}
// MARK: - Private
override func refreshUI() {
super.refreshUI()
let allSeismics = EQNManager.manager().retiSismiche
seismics = EQNSeismic.shared.filterSeismicList(allSeismics ?? [])
tableView?.reloadData()
}
// MARK: - Actions
@IBAction func refreshDataTapped(_ sender: Any) {
EQNManager.manager().sincronizza()
}
@IBAction func openFilterTapped(_ sender: Any) {
performSegue(withIdentifier: Self.SegueIdentifierFilters, sender: nil)
}
@IBAction func openSettingsTapped(_ sender: Any) {
performSegue(withIdentifier: Self.SegueIdentifierSettings, sender: nil)
}
// MARK: - Table view delegate and data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
seismics.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SeismicNetworkTableViewCell.Identifier, for: indexPath) as! SeismicNetworkTableViewCell
let seismic = seismics[indexPath.row]
var type = SeismicNetworkTableViewCell.DisplayType.normal
if openMapIndexPath == indexPath {
type = .mapExpanded
} else if openWeatherIndexPath == indexPath {
type = .weatherExpanded
}
cell.configure(with: seismic, type: type, informations: [ .time, .distance, .location, .population ])
cell.delegate = self
return cell
}
// MARK: - Private
private func openCalendar(for seismic: EQNSisma) {
checkCalendarPermission {
self.createCalendarEvent(for: seismic)
} failure: {
let alert = UIAlertController(title: "Attenzione", message: "Non è possibile aprire il calendario, assicurarsi di aver impostato i permessi corretti", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.present(alert, animated: true)
}
}
private func checkCalendarPermission(success: @escaping () -> Void, failure: @escaping () -> Void) {
let authorization = EKEventStore.authorizationStatus(for: .event)
switch authorization {
case .notDetermined:
let eventStore = EKEventStore()
eventStore.requestAccess(to: .event) { (granted, error) in
DispatchQueue.main.async {
if granted {
success()
} else {
failure()
}
}
}
case .authorized:
success()
default:
failure()
}
}
private func createCalendarEvent(for seismic: EQNSisma) {
let eventStore = EKEventStore()
// calendar event
let event = EKEvent(eventStore: eventStore)
event.title = seismic.place
event.startDate = seismic.date
event.endDate = seismic.date
event.notes = String(format: NSLocalizedString("calendar_description_nogeo_km", comment: ""), seismic.magnitude, seismic.depth)
// controller to present
let eventVC = EKEventEditViewController()
eventVC.editViewDelegate = self
eventVC.eventStore = eventStore
eventVC.event = event
present(eventVC, animated: true)
}
}
extension SeismicNetworksViewController: SeismicNetworkTableViewCellDelegate {
func seismicNetworkCellDidTapShare(_ cell: SeismicNetworkTableViewCell) {
// create a snapshot of the cell and share with default share sheet
let snapshot = cell.createSnapshot()
let controller = UIActivityViewController(activityItems: [snapshot], applicationActivities: [])
present(controller, animated: true)
}
func seismicNetworkCellDidTapWeather(_ cell: SeismicNetworkTableViewCell) {
guard let index = tableView?.indexPath(for: cell) else { return }
let indexToReloads = [openMapIndexPath, openWeatherIndexPath, index].compactMap { $0 }
openWeatherIndexPath = index
openMapIndexPath = nil
tableView?.reloadRows(at: indexToReloads, with: .automatic)
}
func seismicNetworkCellDidTapMap(_ cell: SeismicNetworkTableViewCell) {
guard let index = tableView?.indexPath(for: cell) else { return }
let indexToReloads = [openMapIndexPath, openWeatherIndexPath, index].compactMap { $0 }
openMapIndexPath = index
openWeatherIndexPath = nil
tableView?.reloadRows(at: indexToReloads, with: .automatic)
}
func seismicNetworkCellDidTapCalendar(_ cell: SeismicNetworkTableViewCell) {
guard let index = tableView?.indexPath(for: cell) else { return }
let seismic = seismics[index.row]
openCalendar(for: seismic)
}
func seismicNetworkCellDidTapSettings(_ cell: SeismicNetworkTableViewCell) {
// todo
}
func seismicNetworkCellDidTapClose(_ cell: SeismicNetworkTableViewCell) {
guard let index = tableView?.indexPath(for: cell) else { return }
let indexToReloads = [openMapIndexPath, openWeatherIndexPath, index].compactMap { $0 }
openMapIndexPath = nil
openWeatherIndexPath = nil
tableView?.reloadRows(at: indexToReloads, with: .automatic)
}
}
extension SeismicNetworksViewController: EKEventEditViewDelegate {
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
dismiss(animated: true, completion: nil)
}
}