//
//  NoPassRNBridgeRegistrationiOS.swift
//  SdkTest
//
//  Created by Artsiom Shmaenkov on 18.06.21.
//

import Foundation
import NoPassSDKReact
import React

@objc(NoPassRNBridgeRegistrationiOS)
public class NoPassRNBridgeRegistrationiOS: NSObject, RCTBridgeModule {
    
    public static func moduleName() -> String! {
        return "NoPassRNBridgeRegistrationiOS"
    }
    
    public static func requiresMainQueueSetup() -> Bool {
        return true
    }
    
    @objc public func startRegistration(_ data: String, biometricType: String, isScreenLock: Bool) {
        DispatchQueue.main.async {
            if let type = BiometricType(rawValue: biometricType) {
                NoPassRegistrationService.shared.delegate = self
                print("Start registration flow!!!")
                NoPassRegistrationService.shared.startRegistration(result: data,
                                                                   enabled2FaMethod: type,
                                                                   isScreenLock: isScreenLock)
            }
        }
    }
}

extension NoPassRNBridgeRegistrationiOS: NoPassRegistrationServiceDelegate {
    public func registrationCode(code: String, isNeedConfirmationCode: Bool) {
        EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onRegistrationCodeDidReceiveListener.rawValue, body: ["code": code, "isNeedConfirmationCode": isNeedConfirmationCode])
    }
    
    public func registration(account: NoPassAccount?, error: NopassError?) {
        if let error = error {
            EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onRegistrationDidFailListener.rawValue, body: ["error" : error.errorDescription])
        } else {
            EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onRegistrationDidFinishListener.rawValue, body: ["account" : account?.toDictionaryForRN()])
        }
    }
}
