//
//  SDKModule.swift
//  Pods
//
//  Created by Asti Manuka on 01/10/23.
//

import CastlabsApple
import CoreMedia
import Foundation
import PRESTOplay

// MARK: - SDKModule

@objc(SDKModule)
class SDKModule: NSObject, RCTBridgeModule {
    @objc var moduleRegistry: RCTModuleRegistry!

    static func moduleName() -> String! {
        return "SDKModule"
    }

    static func requiresMainQueueSetup() -> Bool {
        return true
    }

    // MARK: Lifecycle

    override init() {
        super.init()
    }

    init(moduleRegistry: RCTModuleRegistry!) {
        self.moduleRegistry = moduleRegistry
    }

    // MARK: Internal
    @objc
    func initialize(
        _ config: NSDictionary,
        companionSdkInfo: NSDictionary,
        resolver resolve: @escaping RCTPromiseResolveBlock,
        rejecter reject: @escaping RCTPromiseRejectBlock
    ) {
        DispatchQueue.main.async { [weak self] in
            guard let self else { return }
            
            let logLevel = config["logLevel"] as! Int
            PRESTOplaySDK.shared.setLogLevel(getLogLevel(reactLogLevel: logLevel))

            let licenseKey = config["licenseKey"] as! String

            // swiftlint:disable force_cast
            let companion = CompanionSDK(
                name: companionSdkInfo["name"] as! String,
                version: companionSdkInfo["version"] as! String
            )
            // swiftlint:enable force_cast

            var pluginFactories: [PluginFactoryProtocol] = []

            if let pluginFactoryModuleNames = config["pluginFactoryModuleNames"] as? [String] {
                for pluginFactoryModuleName in pluginFactoryModuleNames {
                    if let pluginFactory = moduleRegistry.module(forName: pluginFactoryModuleName)
                        as? PluginFactoryProtocol
                    {
                        pluginFactories.append(pluginFactory)
                    } else if let module = moduleRegistry.module(forName: pluginFactoryModuleName)
                        as? PluginFactoryProtocolNewArch
                    {
                        // New Arch PluginFactoryProtocolNewArch
                        let pluginFactory = module.getSwiftInstance() as! PluginFactoryProtocol
                        pluginFactories.append(pluginFactory)
                    } else {
                        print(
                            "[SDKModule]: Module not found: ", pluginFactoryModuleName,
                            moduleRegistry.module(forName: pluginFactoryModuleName))
                    }
                }
            }

            var appleSdkPlugins: [CLPluginProtocol] = [HLSPlugin()]
            for pluginFactory in pluginFactories {
                let plugin = pluginFactory.getPlugin()
                Repository.shared.plugins.append(plugin)
                appleSdkPlugins.append(contentsOf: plugin.onSdkWillInitialize())
            }

            let licenseCheck = PRESTOplaySDK.shared.register(
                licenseKey,
                appleSdkPlugins,
                companion
            )

            if licenseCheck == .ok {
                resolve(nil)
            } else {
                Rejecter(reject).reject(PrestoPlayError(.fatal, .sdkInvalidLicense))
            }
        }
    }
    
    private func getLogLevel(reactLogLevel:Int) -> CLLogLevel {
        switch reactLogLevel {
            case 0:
                return .none
            case 1, 2, 3:
                return .error
            case 4:
                fallthrough
            default:
                return .debug
            }
    }
}
