import type { GLTF } from "three/examples/jsm/loaders/GLTFLoader.js";

import { AnimationUtils } from "../engine/engine_animation.js";
import { ContextEvent, ContextRegistry } from "../engine/engine_context_registry.js";
import { Animation } from "./Animation.js";
import { Animator } from "./Animator.js";
import { GameObject } from "./Component.js";
import { PlayableDirector } from "./timeline/PlayableDirector.js";

let initialized = false;

export function initAnimationAutoplay() {
    if (initialized) return;
    initialized = true;

    ContextRegistry.registerCallback(ContextEvent.ContextCreated, args => {
    const autoplay = args.context.domElement.getAttribute("autoplay");
    if (autoplay !== undefined && (autoplay === "" || autoplay === "true" || autoplay === "1")) {
        if (args.files) {
            for (const file of args.files) {
                const hasAnimation = GameObject.foreachComponent(file.file.scene, comp => {
                    if (comp.enabled === false) return undefined;
                    if (comp instanceof Animation && comp.playAutomatically || comp instanceof Animator || comp instanceof PlayableDirector && comp.playOnAwake === true) {
                        return true;
                    }
                    else if (comp instanceof Animation) {
                        comp.playAutomatically = true;
                        return true;
                    }
                    else if (comp instanceof PlayableDirector) {
                        comp.playOnAwake = true;
                        return true;
                    }
                    return undefined;
                }, true);
                if (hasAnimation !== true) {
                    AnimationUtils.autoplayAnimations(file.file as GLTF);
                }
            }
        }
    }
});
}
