

from .NEEDLE_persistent_assets_importer import importAnimatorController
from ..utils_debug import debug_err, debug_warn
from .extensionbase import ExtensionBase


class NEEDLE_persistent_assets(ExtensionBase):

    def onBeforeExport(self, exportContext):
        super().onBeforeExport(exportContext)
        self.registered_assets = []
        pass

    def registerSerializedAsset(self, asset) -> str:
        index = len(self.registered_assets)
        self.registered_assets.append(asset)
        if not "guid" in asset:
            debug_warn("Missing guid in asset at index " + str(index) + "!")
        return "/extensions/NEEDLE_persistent_assets/" + str(index)

        
    
    def gather_gltf_extensions_hook(self, gltf2_object, export_settings):
        if len(self.registered_assets) <= 0:
            return
        obj = {
            "assets": self.registered_assets
        }
        gltf2_object.extensions['NEEDLE_persistent_assets'] = obj
        gltf2_object.extensions_used.append("NEEDLE_persistent_assets")
        pass





    def resolveJsonPointerImport(self, jsonPointer) -> any:
        if not jsonPointer.startswith("/extensions/NEEDLE_persistent_assets/"):
            return None
        '''Returns the asset at the given pointer or None if it does not exist'''''
        index = int(jsonPointer[len("/extensions/NEEDLE_persistent_assets/"):])

        if not getattr(self, "imported_assets", None):
            self.imported_assets = dict()
        elif index in self.imported_assets:
            return self.imported_assets[index]
    

        
        data = self.gltf.data
        if data is None:
            return
        extensions = getattr(data, "extensions", None)
        if extensions is None:
            return
        persistent_assets = extensions["NEEDLE_persistent_assets"]
        if persistent_assets is None:
            return
        assets = persistent_assets.get("assets", None)
        if assets is None:
            return
        if index < 0 or index >= len(assets):
            self.imported_assets[index] = None
            return None
        
        asset = assets[index]
        type = asset["__type"]
        res = None
        try:
            if type == "AnimatorController":
                res = importAnimatorController(self, asset)
                pass
        except Exception as e:
            debug_err("Failed to import asset of type " + type + "!")
        finally:
            self.imported_assets[index] = res

        return res


    def gather_import_gltf_before_hook(self, gltf):
        '''Called before the gltf is imported, use this callback to store the gltf object for resolving requests later'''
        self.gltf = gltf
       

