'use strict'

const modules = {
    scene: { 
        render: () => {}
    }
}


let modulesRunStrings = []
let modulesIndent = 0


function rulAllModuleInits () {
    Object.keys(modules).forEach(moduleName => {
        if (modules[moduleName].init) {
            modules[moduleName].self = modules[moduleName].init()
        } else {
            modules[moduleName].self = {}
        }
    })
}


async function runModules (frameTime, modulesToRun) {
    for (let i = 0; i < modulesToRun.length; ++i) {
        const moduleData = modulesToRun[i]
        if (moduleData.enabled !== false) {
            const start = moduleData.start || 0
            const duration = moduleData.duration || 9999
            let adjustedFrameTime = frameTime - start
            if (adjustedFrameTime >= 0 && adjustedFrameTime < duration) {
                const moduleType = moduleData.type
                if (modules[moduleType]) {
                    const modulesRunStringsIndex = modulesRunStrings.length
                    modulesRunStrings.push('.')
                    const startTime = window.performance.now()
                    const time = readAtTime(adjustedFrameTime, moduleData.config || {}, moduleData.syncs || {}, 'time', 'float', adjustedFrameTime)

                    const moduleObject = modules[moduleType]
                    try {
                        const selfConfig = calculateConfig(time, moduleData.config || {}, moduleData.syncs || {}, moduleObject.config || [])
                        await moduleObject.render(time, moduleObject.self, selfConfig)
                    }
                    catch (e) {
                        console.log(`${moduleType}.render() failed -> ${e}`)
                    }

                    if (moduleData.children) {
                        modulesIndent++
                        await runModules(time, moduleData.children)
                        modulesIndent--
                    }

                    const endTime = window.performance.now()
                    const duration = endTime - startTime
                    modulesRunStrings[modulesRunStringsIndex] = duration.toFixed(2).padStart(5, ' ') + '  '.repeat(modulesIndent + 1) + moduleType + ':' + (moduleData.name || '...')
                } else {
                    console.warn(`Unknown module type ${moduleType}`)
                }
            }
        }
    }
}

