//
//  ContentView.swift
//  tb-mfa-lib-tests
//
//  Created by inwebo imac on 29/10/2021.
//

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log

struct ContentView: View {

    private var clientLib = TrustBuilderMfaLib(host: Host())
    @State private var showingAlert = false
    @State private var notificationContent: [AnyHashable: Any]?
    
    let pub = NotificationCenter.default.publisher(for: Notification.Name("pushNotification"))
    
    init() {}

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                if let notifContent = notificationContent {
                    Text("Notification received:")
                    Text("tenant alias:  \(notifContent["tntAlias"] as? String ?? "")")
                    Text("user login:  \(notifContent["usrLogin"] as? String ?? "")")
                    Text("token alias:  \(notifContent["tknAlias"] as? String ?? "")")
                    Text("scope:  \(notifContent["scope"] as? String ?? "")")
                    Text("connector alias:  \(notifContent["cnxAlias"] as? String ?? "")")
                    Text("auth session id:  \(notifContent["authSessionId"] as? String ?? "")")
                }
            }.onReceive(pub) { output in
                if let userInfo = output.userInfo {
                    getInfoFromNotif(userInfo)
                }
            }.padding(16)
            // Max 9 Views per Group
            Group {
                EnrollSecureTokenView()
                GetSecureTokensView()
                GetPendingAuthSessionsView()
                AuthorizeView()
                InAppAuthenticateView()
                AuthenticateView()
                CancelAuthView()
                ResetSecretCodeView()
                DeleteLocalSecureTokenView()
            }
            Group {
                ChangeSecretCodeView()
                RegisterPushIdView()
                UpdateSecureTokenFriendlyNameView()
                SealingView()
                ActivationCodeGenerationView()
                ResetCodeGenerationView()
                RegisterBiokeyView()
            }
            Group {
                GetUserSecureTokensView()
                LockSecureTokenView()
                UnlockSecureTokenView()
                DeleteSecureTokenView()
            }
        }.onAppear {
            if JailbreakService.isDeviceJailbroken() {
                showingAlert = true
            }
        }.alert("This app can't be used on a jailbroken device", isPresented: $showingAlert) {Button("OK", role: .cancel) { exit(1)}}
    }
    
    func getInfoFromNotif(_ userInfo: [AnyHashable: Any]) {
        notificationContent = userInfo
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

