//
//  NoPassRNBridgeSynchronisationServiceiOS.swift
//  SdkTest
//
//  Created by Artsiom Shmaenkov on 7.07.21.
//

import Foundation
import NoPassSDKReact
import React

@objc(NoPassRNBridgeSynchronisationServiceiOS)
public class NoPassRNBridgeSynchronisationServiceiOS: NSObject, RCTBridgeModule {
    
    public static func moduleName() -> String! {
        return "NoPassRNBridgeSynchronisationServiceiOS"
    }
    
    public static func requiresMainQueueSetup() -> Bool {
        return true
    }
    
    @objc public static var shared = NoPassRNBridgeSynchronisationServiceiOS()
    
    private override init() {
        super.init()
        NoPassSynchronisationService.shared.delegate = self
    }
    
    @objc public func startSyncAccount(_ encryptedString: String, biometricType: String, isScreenLock: Bool) {
        DispatchQueue.main.async {
            guard let type = BiometricType(rawValue: biometricType) else {
                EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onSynchronisationDidFailListener.rawValue, body: ["error": NoPassRNBridgeError.biometricTypeNotFound.rawValue])
                return
            }
            
            NoPassSynchronisationService.shared.startSyncAccount(result: encryptedString, enabled2FaMethod: type, isScreenLock: isScreenLock)
        }
    }
}

extension NoPassRNBridgeSynchronisationServiceiOS: NoPassSynchronisationServiceDelegate {
    public func synchronisationDidFinish() {
        EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onSynchronisationDidFinishListener.rawValue, body: true)
    }
    
    public func syncRegistrationCode(code: String, isNeedConfirmationCode: Bool) {
        EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onSynchronisationCodeDidReceiveListener.rawValue, body: ["code": code, "isNeedConfirmationCode": isNeedConfirmationCode])
    }
    
    public func accountWasSynchronised(account: NoPassAccount?, error: NopassError?) {
        let body: Dictionary<String, Any?> = ["account": account?.toDictionaryForRN(), "error": error?.errorDescription]
        EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onAccountWasSynchronisedListener.rawValue, body: body)
    }
    
    public func synchronisationDidFail(error: NopassError) {
        EventEmitter.shared.dispatch(name: NoPassRNBridgeEvent.onSynchronisationDidFailListener.rawValue, body: ["error": error.errorDescription])
    }
}
