
import bpy
from bpy.types import Context, Operator
from bpy_extras import asset_utils
from bpy.props import StringProperty
from typing import List, Tuple, Set

from asset_library.common.file_utils import (open_blender_file, 
    synchronize, open_blender_file)

from asset_library.common.functions import get_active_library


class ASSETLIB_OT_open_blend_file(Operator):
    bl_idname = "assetlib.open_blend_file"
    bl_options = {"REGISTER", "UNDO"}
    bl_label = 'Open Blender File'
    bl_description = 'Open blender 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 != 'FILE':
            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]:
        
        lib = get_active_library()

        filepath = lib.library_type.get_active_asset_path()

        open_blender_file(filepath)

        return {'FINISHED'}

    
classes = (
    ASSETLIB_OT_open_blend_file,
)

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

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