import bpy
from bpy.types import Context, Operator
from bpy_extras import asset_utils

from fnmatch import fnmatch
import os
import fnmatch
from os.path import expandvars
from typing import List, Tuple, Set
from pathlib import Path
import subprocess

from asset_library.common.bl_utils import load_col
from asset_library.common.functions import get_active_library



class ASSETLIB_OT_load_asset(Operator):
    bl_idname = "assetlib.load_asset"
    bl_options = {"REGISTER", "UNDO", "INTERNAL"}
    bl_label = 'Load Asset'
    bl_description = 'Link and override asset in current file'

    @classmethod
    def poll(cls, context: Context) -> bool:
        if not asset_utils.SpaceAssetInfo.is_asset_browser(context.space_data):
            cls.poll_message_set("Current editor is not an asset browser")
            return False
        
        lib = get_active_library()
        if not lib or lib.data_type != 'COLLECTION':
            return False
        
        if not context.active_file or 'filepath' not in context.active_file.asset_data:
            cls.poll_message_set("Has not filepath property")
            return False

        return True

    def execute(self, context: Context) -> Set[str]:

        print('Load Asset')

        lib = get_active_library()
       


        asset = context.active_file
        if not asset:
            self.report({"ERROR"}, 'No asset selected')
            return {'CANCELLED'}
        
        active_lib = lib.library_type.get_active_asset_library()
        asset_path = asset.asset_data['filepath']
        asset_path = active_lib.library_type.format_path(asset_path)
        name = asset.name

        ## set mode to object
        if context.mode != 'OBJECT':
            bpy.ops.object.mode_set(mode='OBJECT')
        
        if not Path(asset_path).exists():
            self.report({'ERROR'}, f'Not exists: {asset_path}')
            return {'CANCELLED'}

        print('Load collection', asset_path, name)
        res = load_col(asset_path, name, link=True, override=True, rig_pattern='*_rig')
        if res:
            if res.type == 'ARMATURE':
                self.report({'INFO'}, f'Override rig {res.name}')
            elif res.type == 'EMPTY':
                self.report({'INFO'}, f'Instance collection {res.name}')

        return {'FINISHED'}


### --- REGISTER ---

classes = (
    ASSETLIB_OT_load_asset,
)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)