OnboardingNavigator 2.swift 2.58 KB
Newer Older
domenicw's avatar
domenicw committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
//  OnboardingNavigator.swift
//  Amiv
//
//  Created by Domenic Wüthrich on 18.09.18.
//  Copyright © 2018 Amiv an der ETH. All rights reserved.
//

import Foundation
import UIKit

public class OnboardingNavigator: Navigator {
    
    // MARK: - Variables
    
    let networkManager = NetworkManager<AMIVApiSession>()
    
    public var delegate: OnboardingNavigatorDelegate?
    
    public var rootViewController: UIViewController {
        return self.navigationController
    }
    
    private var navigationController: UINavigationController
    
    // MARK: - Initializers
    
    public init() {
        let info = InfoViewController(model: .create())
        self.navigationController = UINavigationController(rootViewController: info)
        info.delegate = self
    }
    
    // MARK: - Navigation
    
    private func presentLogin() {
        let login = LoginViewController(model: .createOnboarding())
        login.delegate = self
        self.navigationController.present(login, animated: true, completion: nil)
    }
    
}

extension OnboardingNavigator: InfoViewControllerDelegate {
    
    public func buttonPressed() {
        self.presentLogin()
    }
    
    public func smallButtonPressed() {
        self.delegate?.onboardingFinished()
    }
    
}

extension OnboardingNavigator: LoginViewControllerDelegate {
    
    public func login(_ viewController: LoginViewController, username: String, password: String) {
        // TODO: - Check for valid credentials
        debugPrint("Logging in with username: \(username) and password: \(password)")
        
        
        self.networkManager.authenticate(username: username, password: password) { (response, error) in
            guard let response = response else {
                DispatchQueue.main.async {
                    viewController.loginFailed(with: "Incorrect Username or Password.\nPlease try again.")
                }
                return
            }
            
            // Save token into secure and encrypted keychain
            SessionManager.save(response)
            
            let userManager = NetworkManager<AMIVApiUser>()
            userManager.getUserInfo({ (user, error) in
                guard error == nil, let user = user else {
                    return
                }
                let _ = user.saveLocal()
            })
            
            DispatchQueue.main.async {
                self.delegate?.onboardingFinished()
            }
        }
    }
    
    public func smallButtonTapped(_ viewController: LoginViewController) {
        self.delegate?.onboardingFinished()
    }
    
}