//
//  PluginManager+DefineLoadingStates.swift
//  ZappApple
//
//  Created by Alex Zchut on 07/10/2021.
//  Copyright © 2021 Applicaster LTD. All rights reserved.
//

import Foundation

@available(iOS 15, tvOS 15, *)
extension PluginsManager {
    func intializePlugins() async -> Bool {
        logger?.debugLog(template: PluginsManagerLogs.pluginsInitialization)
        let stateMachine = AsyncLoadingStateMachine(dataSource: self,
                                                    withStates: asyncPrepareLoadingStates())

        _ = await stateMachine.startStatesInvocation()
        return await withCheckedContinuation { continuation in
            pluginLoaderCompletion = { success in
                continuation.resume(returning: success)
            }
        }
    }
    
    func asyncPrepareLoadingStates() -> [AsyncLoadingState] {
        let onLaunchHook = AsyncLoadingState()
        onLaunchHook.asyncStateHandler = hookOnLaunch
        onLaunchHook.readableName = "<plugins-state-machine> Execute Hook Plugin On Launch"

        let analytics = AsyncLoadingState()
        analytics.asyncStateHandler = prepareAnalyticsPlugins
        analytics.dependantStates = [onLaunchHook.name]
        analytics.readableName = "<plugins-state-machine> Prepare Analytics Plugins"

        let push = AsyncLoadingState()
        push.asyncStateHandler = preparePushPlugins
        push.dependantStates = [onLaunchHook.name]
        push.readableName = "<plugins-state-machine> Prepare Push Plugins"

        let general = AsyncLoadingState()
        general.asyncStateHandler = prepareGeneralPlugins
        general.dependantStates = [onLaunchHook.name]
        general.readableName = "<plugins-state-machine> Prepare General Plugins"

        let cmp = AsyncLoadingState()
        cmp.asyncStateHandler = prepareGeneralCmpPlugins
        cmp.dependantStates = [onLaunchHook.name]
        cmp.readableName = "<plugins-state-machine> Prepare Cmp Plugins"

        let player = AsyncLoadingState()
        player.asyncStateHandler = preparePlayerPlugins
        player.dependantStates = [onLaunchHook.name]
        player.readableName = "<plugins-state-machine> Prepare Player Plugins"

        let pluginsSessionStorageData = AsyncLoadingState()
        pluginsSessionStorageData.asyncStateHandler = updatePluginSessionStorageData
        pluginsSessionStorageData.readableName = "<plugins-state-machine> Plugins Session Storage"
        pluginsSessionStorageData.dependantStates = [onLaunchHook.name]

        return [onLaunchHook,
                analytics,
                push,
                general,
                player,
                cmp,
                pluginsSessionStorageData]
    }
}
