//
//  RegisterPushIdView.swift
//  tb-mfa-lib-tests
//
//  Created by inwebo imac on 02/11/2021.
//

import SwiftUI
import TrustBuilderMfaLibSwift
import os.log
import FirebaseMessaging

struct RegisterPushIdView: View {
    @EnvironmentObject var buttonBlock: ButtonBlock
    @State private var result: String = ""

    init() { }

    var body: some View {
        VStack {
            Text("Register push id")
            Button("Execute", action: execute).disabled(buttonBlock.buttonIsBlocked)
            Text(result)
                    .font(.footnote)
                    .foregroundColor(.red)
        }
                .buttonStyle(.bordered)
                .textFieldStyle(RoundedBorderTextFieldStyle())
    }

    func execute() {
        Task.init {
            buttonBlock.buttonIsBlocked = true
            defer { buttonBlock.buttonIsBlocked = false }
            do {
                if let pushId = Messaging.messaging().fcmToken {
                    let useCase = try TrustBuilderMfaLibHolder.getLibInstance().startPushIdRegistration(param: PushIdRegistrationParams(tknPushId: pushId))
                    let response = try await useCase.execute()
                    let jsonEncoder = JSONEncoder()
                    let jsonData = try jsonEncoder.encode(response)
                    result = String(data: jsonData, encoding: String.Encoding.utf8)!
                } else {
                    result = "No pushId available, please verify that you enabled push notification in your app settings"
                }
            } catch {
                os_log("Task failed: %@", log: .default, type: .error, String(describing: error))
                result = String(describing: error)
            }
        }
    }
}
