DashboardViewController.swift 27.6 KB
Newer Older
Davide De Rosa's avatar
Davide De Rosa committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
//  DashboardViewController.swift
//  PIA VPN
//
//  Created by Davide De Rosa on 12/7/17.
//  Copyright © 2017 London Trust Media. All rights reserved.
//

import UIKit
import PIALibrary
import SideMenu
import SwiftyBeaver

private let log = SwiftyBeaver.self

class DashboardViewController: AutolayoutViewController {
Jose Blaya's avatar
Jose Blaya committed
17
    
18 19 20 21
    private enum TileSize: CGFloat {
        case standard = 89.0
    }
    
Jose Blaya's avatar
Jose Blaya committed
22 23 24 25 26
    private enum Cells: Int, EnumsBuilder {
        
        case region = 0
        case quickConnect
        case ipTile
Jose Blaya's avatar
wip  
Jose Blaya committed
27
        case subscription
Jose Blaya's avatar
Jose Blaya committed
28
        case usage
Jose Blaya's avatar
Jose Blaya committed
29
        case networkManagementTool
Jose Blaya's avatar
wip  
Jose Blaya committed
30

Jose Blaya's avatar
Jose Blaya committed
31 32 33 34 35
        var identifier: String {
            switch self {
            case .ipTile: return "IPTileCell"
            case .quickConnect: return "QuickConnectTileCell"
            case .region: return "RegionTileCell"
Jose Blaya's avatar
wip  
Jose Blaya committed
36
            case .subscription: return "SubscriptionTileCell"
Jose Blaya's avatar
Jose Blaya committed
37
            case .usage: return "UsageTileCell"
Jose Blaya's avatar
Jose Blaya committed
38
            case .networkManagementTool: return "NMTTileCell"
Jose Blaya's avatar
Jose Blaya committed
39 40 41 42 43 44 45 46
            }
        }
        
        var className: String {
            switch self {
            case .ipTile: return "IPTileCollectionViewCell"
            case .quickConnect: return "QuickConnectTileCollectionViewCell"
            case .region: return "RegionTileCollectionViewCell"
Jose Blaya's avatar
wip  
Jose Blaya committed
47
            case .subscription: return "SubscriptionTileCollectionViewCell"
Jose Blaya's avatar
Jose Blaya committed
48
            case .usage: return "UsageTileCollectionViewCell"
Jose Blaya's avatar
Jose Blaya committed
49
            case .networkManagementTool: return "NetworkManagementToolTileCollectionViewCell"
Jose Blaya's avatar
Jose Blaya committed
50 51
            }
        }
Davide De Rosa's avatar
Davide De Rosa committed
52 53
    }
    
Jose Blaya's avatar
Jose Blaya committed
54 55 56
    private var viewContentHeight: CGFloat = 0
    @IBOutlet weak var viewContentHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var viewContentLandscapeHeightConstraint: NSLayoutConstraint!
Davide De Rosa's avatar
Davide De Rosa committed
57
    
Jose Blaya's avatar
Jose Blaya committed
58
    @IBOutlet private weak var viewContent: UIView!
59
    @IBOutlet private weak var toggleConnection: PIAConnectionButton!
Davide De Rosa's avatar
Davide De Rosa committed
60 61 62
    
    @IBOutlet private weak var viewRows: UIView!
    
Jose Blaya's avatar
Jose Blaya committed
63
    @IBOutlet private weak var collectionView: UICollectionView!
Davide De Rosa's avatar
Davide De Rosa committed
64 65 66 67 68
    
    private var currentPageIndex = 0
    
    private var currentStatus: VPNStatus = .disconnected

Jose Blaya's avatar
Jose Blaya committed
69 70 71 72 73 74
    private var tileModeStatus: TileStatus = .normal {
        didSet {
            self.updateTileLayout()
        }
    }

Davide De Rosa's avatar
Davide De Rosa committed
75 76 77 78 79 80
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
Jose Blaya's avatar
Jose Blaya committed
81
        
Jose Blaya's avatar
wip  
Jose Blaya committed
82
        setupCollectionView()
83 84
        setupNavigationBarButtons()
        
Davide De Rosa's avatar
Davide De Rosa committed
85 86 87 88 89
        viewContent.isHidden = true
        viewRows.isHidden = true
        
        currentPageIndex = 0

Davide De Rosa's avatar
Davide De Rosa committed
90
        SideMenuManager.default.menuLeftNavigationController = StoryboardScene.Main.sideMenuNavigationController.instantiate()
91 92
        SideMenuManager.default.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
        SideMenuManager.default.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
Davide De Rosa's avatar
Davide De Rosa committed
93 94 95 96 97 98

        let nc = NotificationCenter.default
        nc.addObserver(self, selector: #selector(accountDidLogout(notification:)), name: .PIAAccountDidLogout, object: nil)
        nc.addObserver(self, selector: #selector(vpnDidInstall(notification:)), name: .PIAVPNDidInstall, object: nil)
        nc.addObserver(self, selector: #selector(applicationDidBecomeActive(notification:)), name: .UIApplicationDidBecomeActive, object: nil)
        nc.addObserver(self, selector: #selector(vpnStatusDidChange(notification:)), name: .PIADaemonsDidUpdateVPNStatus, object: nil)
Jose Blaya's avatar
Jose Blaya committed
99
        nc.addObserver(self, selector: #selector(viewHasRotated), name: .UIDeviceOrientationDidChange, object: nil)
Jose Blaya's avatar
Jose Blaya committed
100
        nc.addObserver(self, selector: #selector(updateCurrentStatus), name: .PIAThemeDidChange, object: nil)
101
        nc.addObserver(self, selector: #selector(updateTiles), name: .PIATilesDidChange, object: nil)
Jose Blaya's avatar
Jose Blaya committed
102
        nc.addObserver(self, selector: #selector(vpnShouldReconnect), name: .PIASettingsHaveChanged, object: nil)
Davide De Rosa's avatar
Davide De Rosa committed
103 104 105 106 107 108 109 110 111 112

#if !TARGET_IPHONE_SIMULATOR
        let types: UIUserNotificationType = [.alert, .badge, .sound]
        let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: types, categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
#endif

        if Client.providers.accountProvider.isLoggedIn {
            Client.providers.accountProvider.refreshAndLogoutUnauthorized()
        }
Jose Blaya's avatar
Jose Blaya committed
113
        
Jose Blaya's avatar
Jose Blaya committed
114
        self.viewContentHeight = self.viewContentHeightConstraint.constant
Davide De Rosa's avatar
Davide De Rosa committed
115 116 117 118 119
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
120 121
        setupNavigationBarButtons()

Davide De Rosa's avatar
Davide De Rosa committed
122 123 124 125 126 127 128 129 130 131 132 133 134
        guard AppPreferences.shared.wasLaunched && !Flags.shared.alwaysShowsWalkthrough else {
            AppPreferences.shared.wasLaunched = true
            showWalkthrough()
            return
        }
        guard Client.providers.accountProvider.isLoggedIn else {
            presentLogin()
            return
        }

        viewContent.isHidden = false
        viewRows.isHidden = false

Jose Blaya's avatar
Jose Blaya committed
135
        collectionView.reloadData()
Davide De Rosa's avatar
Davide De Rosa committed
136 137 138 139 140 141 142 143 144
        updateCurrentStatus()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        guard Client.providers.accountProvider.isLoggedIn else {
            return
        }
145 146 147 148 149 150 151
        if Flags.shared.enablesContentBlockerSetting {
            guard AppPreferences.shared.didSeeContentBlocker else {
                AppPreferences.shared.didSeeContentBlocker = true
                let alert = Macros.alert(
                    L10n.Settings.ContentBlocker.title,
                    L10n.Dashboard.ContentBlocker.Intro.message
                )
152 153
                alert.addActionWithTitle(L10n.Global.ok) {
                }
154 155 156
                present(alert, animated: true, completion: nil)
                return
            }
Davide De Rosa's avatar
Davide De Rosa committed
157 158 159 160 161 162 163 164 165 166 167 168
        }
    
        if TransientState.shouldDisplayRegionPicker {
            TransientState.shouldDisplayRegionPicker = false
            selectRegion(animated: false)
        }

        // give up pending signup if logged in
        TransientState.didRetryPendingSignup = true
    }
    
    // MARK: Actions
169 170
    private func setupNavigationBarButtons() {
        
171 172 173 174 175 176 177 178
        guard AppPreferences.shared.wasLaunched,
            !Flags.shared.alwaysShowsWalkthrough,
            Client.providers.accountProvider.isLoggedIn else {
            navigationItem.leftBarButtonItem = nil
            navigationItem.rightBarButtonItem = nil
            return
        }

179 180
        switch self.tileModeStatus { //change the status
        case .normal:
Jose Blaya's avatar
Jose Blaya committed
181 182 183 184 185 186 187 188 189 190 191 192
            if let leftBarButton = navigationItem.leftBarButtonItem,
                leftBarButton.accessibilityLabel != L10n.Global.cancel {
                leftBarButton.image = Asset.itemMenu.image
                leftBarButton.action = #selector(openMenu(_:))
            } else {
                navigationItem.leftBarButtonItem = UIBarButtonItem(
                    image: Asset.itemMenu.image,
                    style: .plain,
                    target: self,
                    action: #selector(openMenu(_:))
                )
            }
193 194
            navigationItem.leftBarButtonItem?.accessibilityLabel = L10n.Menu.Accessibility.item
            
Jose Blaya's avatar
Jose Blaya committed
195 196 197 198 199 200 201 202 203 204
            if navigationItem.rightBarButtonItem == nil {
                navigationItem.rightBarButtonItem = UIBarButtonItem(
                    image: Asset.Piax.Global.iconEditTile.image,
                    style: .plain,
                    target: self,
                    action: #selector(updateEditTileStatus(_:))
                )
                navigationItem.rightBarButtonItem?.accessibilityLabel = L10n.Menu.Accessibility.Edit.tile
            }
            
205
        case .edit:
Jose Blaya's avatar
Jose Blaya committed
206
            
207 208 209 210 211 212 213
            navigationItem.leftBarButtonItem = UIBarButtonItem(
                barButtonSystemItem: .stop,
                target: self,
                action: #selector(closeTileEditingMode(_:))
            )
            navigationItem.leftBarButtonItem?.accessibilityLabel = L10n.Global.cancel
            navigationItem.rightBarButtonItem = nil
Jose Blaya's avatar
Jose Blaya committed
214
            
215
        }
Jose Blaya's avatar
Jose Blaya committed
216
        
217
    }
Jose Blaya's avatar
Jose Blaya committed
218

Jose Blaya's avatar
wip  
Jose Blaya committed
219 220 221 222 223 224 225 226 227 228 229 230 231
    private func setupCollectionView() {
        collectionView.register(UINib(nibName: Cells.ipTile.className,
                                      bundle: nil),
                                forCellWithReuseIdentifier: Cells.ipTile.identifier)
        collectionView.register(UINib(nibName: Cells.quickConnect.className,
                                      bundle: nil),
                                forCellWithReuseIdentifier: Cells.quickConnect.identifier)
        collectionView.register(UINib(nibName: Cells.region.className,
                                      bundle: nil),
                                forCellWithReuseIdentifier: Cells.region.identifier)
        collectionView.register(UINib(nibName: Cells.subscription.className,
                                      bundle: nil),
                                forCellWithReuseIdentifier: Cells.subscription.identifier)
Jose Blaya's avatar
Jose Blaya committed
232 233 234
        collectionView.register(UINib(nibName: Cells.usage.className,
                                      bundle: nil),
                                forCellWithReuseIdentifier: Cells.usage.identifier)
Jose Blaya's avatar
Jose Blaya committed
235 236 237
        collectionView.register(UINib(nibName: Cells.networkManagementTool.className,
                                      bundle: nil),
                                forCellWithReuseIdentifier: Cells.networkManagementTool.identifier)
Jose Blaya's avatar
wip  
Jose Blaya committed
238 239 240
        collectionView.backgroundColor = .clear
    }
    
Jose Blaya's avatar
Jose Blaya committed
241 242 243 244 245 246 247
    private func updateTileLayout() {
        UIView.animate(withDuration: AppConfiguration.Animations.duration, animations: {
            self.toggleConnection.alpha = self.tileModeStatus == .normal ? 1 : 0
            self.viewContentHeightConstraint.constant = self.tileModeStatus == .normal ? self.viewContentHeight : 0
            self.viewContentLandscapeHeightConstraint.constant = self.tileModeStatus == .normal ? self.viewContentHeight : 0
            self.view.layoutIfNeeded()
        })
Jose Blaya's avatar
Jose Blaya committed
248
        collectionView.reloadData()
249
        setupNavigationBarButtons()
Jose Blaya's avatar
Jose Blaya committed
250
    }
Davide De Rosa's avatar
Davide De Rosa committed
251 252 253 254 255 256 257 258 259 260 261 262
    
    private func showWalkthrough() {
        perform(segue: StoryboardSegue.Main.walkthroughSegueIdentifier)
    }
    
    private func presentLogin() {
        var preset = AppConfiguration.Welcome.defaultPreset()
        preset.shouldRecoverPendingSignup = false//!TransientState.didRetryPendingSignup
        if !TransientState.didRetryPendingSignup {
            TransientState.didRetryPendingSignup = true
        }

263
        let vc = GetStartedViewController.with(preset: preset, delegate: self)
Jose Blaya's avatar
Jose Blaya committed
264 265 266
        
        if let presented = self.navigationController?.presentedViewController,
            presented != self {
267 268
            self.present(vc, animated: true, completion: {
                presented.dismiss(animated: true, completion: nil)
Jose Blaya's avatar
Jose Blaya committed
269 270 271 272
            })
        } else {
            present(vc, animated: false, completion: nil)
        }
Davide De Rosa's avatar
Davide De Rosa committed
273 274 275 276 277 278 279 280
    }
    
    private func presentPurchaseForTrial() {
        var preset = AppConfiguration.Welcome.defaultPreset()
        preset.pages = .purchase
        preset.allowsCancel = true
        preset.shouldRecoverPendingSignup = false
        preset.isEphemeral = true
281
        preset.openFromDashboard = true
Davide De Rosa's avatar
Davide De Rosa committed
282

283
        let vc = GetStartedViewController.withPurchase(preset: preset, delegate: self)
Davide De Rosa's avatar
Davide De Rosa committed
284 285 286 287 288 289 290
        present(vc, animated: true, completion: nil)
    }
    
    @objc private func openMenu(_ sender: Any?) {
        perform(segue: StoryboardSegue.Main.menuSegueIdentifier)
    }
    
291 292 293 294
    @objc private func closeTileEditingMode(_ sender: Any?) {
        self.tileModeStatus = .normal
    }
    
Jose Blaya's avatar
Jose Blaya committed
295 296 297 298 299 300 301 302 303
    @objc private func updateEditTileStatus(_ sender: Any?) {
        switch self.tileModeStatus { //change the status
        case .normal:
            self.tileModeStatus = .edit
        case .edit:
            self.tileModeStatus = .normal
        }
    }

304 305
    @IBAction func vpnButtonClicked(_ sender: Any?) {
        if !toggleConnection.isOn {
Jose Blaya's avatar
Jose Blaya committed
306 307 308
            Client.providers.vpnProvider.connect({ [weak self] _ in
                self?.reloadUsageTileAfter(seconds: 5) //Show some usage after 5 seconds of activity
            })
Jose Blaya's avatar
Jose Blaya committed
309 310 311
            NotificationCenter.default.post(name: .PIAServerHasBeenUpdated,
                                            object: self,
                                            userInfo: nil)
Davide De Rosa's avatar
Davide De Rosa committed
312
        } else {
313 314 315 316 317 318 319 320 321 322 323 324
            
            var showAlert = false
            if let ssid = UIDevice.current.WiFiSSID {
                if (Client.preferences.useWiFiProtection && (!Client.preferences.trustedNetworks.contains(ssid) || Client.preferences.shouldConnectForAllNetworks)) {
                    showAlert = true
                }
            } else {
                if !Client.preferences.trustCellularData {
                    showAlert = true
                }
            }
            
Jose Blaya's avatar
Jose Blaya committed
325 326 327 328
            if !Client.preferences.nmtRulesEnabled { //if NMT disabled...
                showAlert = false
            }
            
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            if showAlert {
                let alert = Macros.alert(
                    nil,
                    L10n.Dashboard.Vpn.Disconnect.untrusted
                )
                
                alert.addCancelActionWithTitle(L10n.Global.cancel) {
                }
                
                alert.addActionWithTitle(L10n.Shortcuts.disconnect) {
                    self.disconnectWithOneSecondDelay()
                }
                
                present(alert, animated: true, completion: nil)
            } else {
                disconnectWithOneSecondDelay()
            }
Jose Blaya's avatar
Jose Blaya committed
346 347 348 349
        }
        Macros.postNotification(.PIAVPNUsageUpdate)
    }
    
350 351 352 353 354 355
    private func disconnectWithOneSecondDelay() {
        Client.providers.vpnProvider.disconnect({ [weak self] _ in
            self?.reloadUsageTileAfter(seconds: 1) //Reset the usage statistics after stop the VPN
        })
    }
    
Jose Blaya's avatar
Jose Blaya committed
356 357 358
    private func reloadUsageTileAfter(seconds: TimeInterval) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            Macros.postNotification(.PIAVPNUsageUpdate)
Davide De Rosa's avatar
Davide De Rosa committed
359 360 361 362 363 364 365 366 367 368 369
        }
    }
    
    @IBAction private func selectRegion(_ sender: Any?) {
        selectRegion(animated: true)
    }
    
    func selectRegion(animated: Bool) {
        let segue = (animated ? StoryboardSegue.Main.selectRegionAnimatedSegueIdentifier : StoryboardSegue.Main.selectRegionSegueIdentifier)
        perform(segue: segue)
    }
Jose Blaya's avatar
Jose Blaya committed
370 371 372 373

    func openSettings() {
        perform(segue: StoryboardSegue.Main.settingsSegueIdentifier)
    }
Jose Blaya's avatar
Jose Blaya committed
374 375 376 377
    
    func openAccount() {
        perform(segue: StoryboardSegue.Main.accountSegueIdentifier)
    }
Jose Blaya's avatar
Jose Blaya committed
378

379 380 381 382
    func openAbout() {
        perform(segue: StoryboardSegue.Main.aboutSegueIdentifier)
    }

Davide De Rosa's avatar
Davide De Rosa committed
383 384 385 386 387 388 389 390
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        navigationItem.setEmptyBackButton()

        if let sideMenu = segue.destination as? UISideMenuNavigationController {
            guard let menu = sideMenu.topViewController as? MenuViewController else {
                return
            }
            menu.delegate = self
Jose Blaya's avatar
Jose Blaya committed
391 392
        } else if let nmt = segue.destination as? TrustedNetworksViewController {
            nmt.shouldReconnectAutomatically = true
Davide De Rosa's avatar
Davide De Rosa committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        }
    }
    
    // MARK: Unwind segues
    
    @IBAction private func unwoundWalkthroughViewController(_ segue: UIStoryboardSegue) {
    }
    
    @IBAction private func unwoundRegionsViewController(_ segue: UIStoryboardSegue) {
    }
    
    // MARK: Notifications

    @objc private func vpnDidInstall(notification: Notification) {
        log.debug("Installed VPN profile!")
    }
    
    @objc private func applicationDidBecomeActive(notification: Notification) {
        perform(#selector(updateCurrentStatus))
    
        if Client.providers.accountProvider.isLoggedIn {
            Client.providers.accountProvider.refreshAndLogoutUnauthorized()
        }
    }
    
Jose Blaya's avatar
Jose Blaya committed
418
    @objc private func viewHasRotated() {
Jose Blaya's avatar
Jose Blaya committed
419 420 421 422 423 424 425
        if Client.providers.accountProvider.isLoggedIn {
            if tileModeStatus == .edit,
                let tileLayout = collectionView.collectionViewLayout as? TileFlowLayout {
                tileLayout.removeDraggingViewFromSuperView()
            }
            updateCurrentStatus()
            updateTileLayout()
426
        }
Jose Blaya's avatar
Jose Blaya committed
427 428
    }

Davide De Rosa's avatar
Davide De Rosa committed
429 430 431 432 433 434 435 436 437 438
    @objc private func accountDidLogout(notification: Notification) {
        presentLogin()
    }
    
    // MARK: Notifications (Connection)
    
    @objc private func vpnStatusDidChange(notification: Notification) {
        performSelector(onMainThread: #selector(updateCurrentStatusWithUserInfo(_:)), with: notification.userInfo, waitUntilDone: false)
    }
    
Jose Blaya's avatar
Jose Blaya committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    @objc private func vpnShouldReconnect() {
        if Client.providers.vpnProvider.vpnStatus != .disconnected {
            let alert = Macros.alert(
                title,
                L10n.Settings.Commit.Messages.shouldReconnect
            )
            
            // reconnect -> reconnect VPN and close
            alert.addActionWithTitle(L10n.Settings.Commit.Buttons.reconnect) {
                Client.providers.vpnProvider.reconnect(after: nil, { error in
                })
            }
            
            // later -> close
            alert.addCancelActionWithTitle(L10n.Settings.Commit.Buttons.later) {
            }
            
            present(alert, animated: true, completion: nil)
        }
    }
    
Davide De Rosa's avatar
Davide De Rosa committed
460 461 462
    // MARK: Helpers

    @objc private func updateCurrentStatus() {
Jose Blaya's avatar
Jose Blaya committed
463
        Macros.postNotification(.PIAVPNUsageUpdate)
Davide De Rosa's avatar
Davide De Rosa committed
464 465 466
        updateCurrentStatusWithUserInfo(nil)
    }
    
467 468 469 470
    @objc private func updateTiles() {
        collectionView.reloadData()
    }

Davide De Rosa's avatar
Davide De Rosa committed
471 472 473 474 475 476 477
    @objc private func updateCurrentStatusWithUserInfo(_ userInfo: [AnyHashable: Any]?) {
        currentStatus = Client.providers.vpnProvider.vpnStatus

        switch currentStatus {
        case .connected:
            toggleConnection.isOn = true
            toggleConnection.isIndeterminate = false
478
            toggleConnection.stopButtonAnimation()
479 480 481 482 483 484 485 486 487 488
            AppPreferences.shared.lastVPNConnectionStatus = .connected
            let titleLabelView = UILabel(frame: CGRect.zero)
            titleLabelView.style(style: TextStyle.textStyle6)
            titleLabelView.text = L10n.Dashboard.Vpn.on.uppercased()
            Theme.current.applyCustomNavigationBar(navigationController!.navigationBar,
                                                   withTintColor: .white,
                                                   andBarTintColors: [UIColor.piaGreen,
                                                                      UIColor.piaGreenDark20])
            navigationItem.titleView = titleLabelView
            setNeedsStatusBarAppearanceUpdate()
Davide De Rosa's avatar
Davide De Rosa committed
489 490 491 492

        case .disconnected:
            toggleConnection.isOn = false
            toggleConnection.isIndeterminate = false
493
            toggleConnection.stopButtonAnimation()
494
            AppPreferences.shared.lastVPNConnectionStatus = .disconnected
495
            resetNavigationBar()
Davide De Rosa's avatar
Davide De Rosa committed
496 497

        case .connecting:
Jose Blaya's avatar
Jose Blaya committed
498
            Macros.postNotification(.PIADaemonsDidUpdateConnectivity)
Jose Blaya's avatar
Jose Blaya committed
499
            toggleConnection.isOn = false
Davide De Rosa's avatar
Davide De Rosa committed
500
            toggleConnection.isIndeterminate = true
501
            toggleConnection.startButtonAnimation()
502 503
            AppPreferences.shared.lastVPNConnectionStatus = .connecting
            let titleLabelView = UILabel(frame: CGRect.zero)
504 505 506
            titleLabelView.style(style: Theme.current.palette.appearance == .dark ?
                TextStyle.textStyle6 :
                TextStyle.textStyle7)
507 508 509 510 511 512
            titleLabelView.text = L10n.Dashboard.Vpn.connecting.uppercased()
            Theme.current.applyCustomNavigationBar(navigationController!.navigationBar,
                                                   withTintColor: nil,
                                                   andBarTintColors: nil)
            navigationItem.titleView = titleLabelView
            setNeedsStatusBarAppearanceUpdate()
Davide De Rosa's avatar
Davide De Rosa committed
513 514 515 516

        case .disconnecting:
            toggleConnection.isOn = true
            toggleConnection.isIndeterminate = true
517
            toggleConnection.startButtonAnimation()
518 519
            AppPreferences.shared.lastVPNConnectionStatus = .disconnecting
            let titleLabelView = UILabel(frame: CGRect.zero)
520 521 522
            titleLabelView.style(style: Theme.current.palette.appearance == .dark ?
                TextStyle.textStyle6 :
                TextStyle.textStyle7)
523 524 525 526 527 528 529
            titleLabelView.text = L10n.Dashboard.Vpn.disconnecting.uppercased()

            Theme.current.applyCustomNavigationBar(navigationController!.navigationBar,
                                                   withTintColor: nil,
                                                   andBarTintColors: nil)
            navigationItem.titleView = titleLabelView
            setNeedsStatusBarAppearanceUpdate()
Davide De Rosa's avatar
Davide De Rosa committed
530 531 532 533 534 535 536 537 538 539 540 541 542 543

//        case .changingServer:
//            powerConnection.powerState = .pending
//            labelStatus.text = L10n.Dashboard.Vpn.changingRegion
        }

    }


    // MARK: Restylable

    override func viewShouldRestyle() {
        super.viewShouldRestyle()

Jose Blaya's avatar
Jose Blaya committed
544
        navigationItem.titleView = NavigationLogoView()
Jose Blaya's avatar
Jose Blaya committed
545 546 547 548
        Theme.current.applyPrincipalBackground(view)
        Theme.current.applyPrincipalBackground(viewContainer!)
        Theme.current.applyPrincipalBackground(viewContent)
        Theme.current.applyPrincipalBackground(viewRows)
Jose Blaya's avatar
Jose Blaya committed
549

Jose Blaya's avatar
Jose Blaya committed
550
        Theme.current.applyLightNavigationBar(navigationController!.navigationBar)
Jose Blaya's avatar
Jose Blaya committed
551
        
Jose Blaya's avatar
Jose Blaya committed
552
        Theme.current.applyPrincipalBackground(collectionView)
Jose Blaya's avatar
Jose Blaya committed
553

Jose Blaya's avatar
Jose Blaya committed
554 555
        collectionView.collectionViewLayout.invalidateLayout()
        collectionView.reloadData()
Davide De Rosa's avatar
Davide De Rosa committed
556
    }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
    
    private func resetNavigationBar() {
        //First reset the green background
        DispatchQueue.main.async {
            Theme.current.applyCustomNavigationBar(self.navigationController!.navigationBar,
                                                   withTintColor: nil,
                                                   andBarTintColors: nil)
            //Show the PIA logo
            self.navigationItem.titleView = NavigationLogoView()
            if let navController = self.navigationController {
                //Apply the theme background color
                Theme.current.applyLightNavigationBar(navController.navigationBar)
            }
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
Davide De Rosa's avatar
Davide De Rosa 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 600 601 602 603 604 605
}

extension DashboardViewController: PIAWelcomeViewControllerDelegate {
    func welcomeController(_ welcomeController: PIAWelcomeViewController, didLoginWith user: UserAccount, topViewController: UIViewController) {
        showVPNModal(target: topViewController)
    }
    
    func welcomeController(_ welcomeController: PIAWelcomeViewController, didSignupWith user: UserAccount, topViewController: UIViewController) {

        // trial account did purchase, replace current user
        if welcomeController.isEphemeral {
            Client.providers.accountProvider.currentUser = user
        }

        showVPNModal(target: topViewController)
    }
    
    func welcomeControllerDidCancel(_ welcomeController: PIAWelcomeViewController) {
        dismiss(animated: true)
    }

    private func showVPNModal(target: UIViewController) {
        let vc = StoryboardScene.Main.vpnPermissionViewController.instantiate()
        vc.dismissingViewController = self
        target.navigationController?.pushViewController(vc, animated: true)
    }
}

extension DashboardViewController: MenuViewControllerDelegate {
    func menu(_ menu: MenuViewController, didSelect item: MenuViewController.Item) {
        switch item {
        case .selectRegion:
            selectRegion(animated: true)
Jose Blaya's avatar
Jose Blaya committed
606 607
        case .settings:
            openSettings()
Jose Blaya's avatar
Jose Blaya committed
608 609
        case .account:
            openAccount()
610 611
        case .about:
            openAbout()
Davide De Rosa's avatar
Davide De Rosa committed
612
        case .logout:
613
            resetNavigationBar()
Davide De Rosa's avatar
Davide De Rosa committed
614 615 616 617 618 619 620 621 622 623 624
            presentLogin()
        default:
            fatalError("Unhandled item '\(item)'")
        }
    }
    
    func menu(didDetectTrialUpgrade: MenuViewController) {
        presentPurchaseForTrial()
    }
}

Jose Blaya's avatar
Jose Blaya committed
625 626 627 628 629
extension DashboardViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
630 631
        return CGSize(width: collectionView.frame.width,
                      height: TileSize.standard.rawValue)
Jose Blaya's avatar
Jose Blaya committed
632 633 634 635 636 637 638 639 640 641 642 643
    }
    
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
    }
    
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
Davide De Rosa's avatar
Davide De Rosa committed
644
    }
Jose Blaya's avatar
Jose Blaya committed
645 646
    
}
Davide De Rosa's avatar
Davide De Rosa committed
647

Jose Blaya's avatar
Jose Blaya committed
648 649

extension DashboardViewController: UICollectionViewDelegate, UICollectionViewDataSource {
Davide De Rosa's avatar
Davide De Rosa committed
650
    
Jose Blaya's avatar
Jose Blaya committed
651
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
Jose Blaya's avatar
Jose Blaya committed
652 653 654
        
        let tileIndex = tileModeStatus == .normal ?
            Client.providers.tileProvider.visibleTiles[indexPath.row].rawValue :
Jose Blaya's avatar
Jose Blaya committed
655
            Client.providers.tileProvider.orderedTiles[indexPath.row].rawValue
Jose Blaya's avatar
Jose Blaya committed
656 657
        
        let identifier = Cells.objectIdentifyBy(index: tileIndex).identifier
Jose Blaya's avatar
Jose Blaya committed
658 659
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier,
                                                      for: indexPath)
Jose Blaya's avatar
Jose Blaya committed
660 661 662
        if let cell = cell as? EditableTileCell {
            cell.setupCellForStatus(self.tileModeStatus)
        }
Jose Blaya's avatar
Jose Blaya committed
663
        return cell
Jose Blaya's avatar
Jose Blaya committed
664 665 666 667 668 669 670
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
671 672 673
        if !Client.providers.accountProvider.isLoggedIn {
            return 0
        }
Jose Blaya's avatar
Jose Blaya committed
674 675
        return tileModeStatus == .normal ?
            Client.providers.tileProvider.visibleTiles.count :
Jose Blaya's avatar
Jose Blaya committed
676
            Client.providers.tileProvider.orderedTiles.count
Davide De Rosa's avatar
Davide De Rosa committed
677
    }
Jose Blaya's avatar
Jose Blaya committed
678
    
Jose Blaya's avatar
Jose Blaya committed
679
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
Jose Blaya's avatar
Jose Blaya committed
680 681 682 683 684 685 686
        if tileModeStatus == .normal {
            let cell = collectionView.cellForItem(at: indexPath)
            if let detailedCell = cell as? DetailedTileCell,
                detailedCell.hasDetailView(),
                let segueIdentifier = detailedCell.segueIdentifier() {
                performSegue(withIdentifier: segueIdentifier, sender: nil)
            }
Jose Blaya's avatar
Jose Blaya committed
687 688
        }
    }
Jose Blaya's avatar
Jose Blaya committed
689 690
    
    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
Jose Blaya's avatar
Jose Blaya committed
691 692
        if tileModeStatus == .normal,
            let cell = collectionView.cellForItem(at: indexPath) as? DetailedTileCell,
Jose Blaya's avatar
Jose Blaya committed
693 694 695 696 697 698 699 700
            cell.hasDetailView() {
            UIView.animate(withDuration: 0.1, animations: {
                cell.highlightCell()
            })
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
Jose Blaya's avatar
Jose Blaya committed
701 702
        if tileModeStatus == .normal,
            let cell = collectionView.cellForItem(at: indexPath) as? DetailedTileCell,
Jose Blaya's avatar
Jose Blaya committed
703 704 705 706 707 708
            cell.hasDetailView() {
            UIView.animate(withDuration: 0.1, animations: {
                cell.unhighlightCell()
            })
        }
    }
Jose Blaya's avatar
Jose Blaya committed
709 710 711 712 713 714 715 716 717 718 719 720
    
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        return self.tileModeStatus == .edit
    }
    
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        var orderedTiles = Client.providers.tileProvider.orderedTiles
        let tile = orderedTiles.remove(at: sourceIndexPath.row)
        orderedTiles.insert(tile, at: destinationIndexPath.row)
        Client.providers.tileProvider.orderedTiles = orderedTiles
        collectionView.reloadData()
    }
Davide De Rosa's avatar
Davide De Rosa committed
721
}