import bpy
from .component_utils import hasComponent, addComponent
from . import component_registry

# https://blender.stackexchange.com/questions/8699/what-ui-would-work-for-choosing-from-a-long-long-list

def createComponentsOptions(self, context):
    options = []
    for key in component_registry.schemes:
        if hasComponent(context.object, key):
            continue
        options.append((key, key, key))
    return options

class WM_OT_selection_popup(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "wm.component_selection"
    bl_label = "Filter"
    bl_property = "component_options"
    component_options: bpy.props.EnumProperty(items=createComponentsOptions)

    # filter: bpy.props.StringProperty(name="Name", default="")
    # target = []

    def execute(self, context):
        selectedComponent = self.component_options
        print("SELECTED", selectedComponent)
        addComponent(context, selectedComponent)
        return {'FINISHED'}

    # def execute(self, context):
    #     text = self.filter
    #     # print(text)
    #     # bpy.data.objects[0].name = str(text)
    #     return {'FINISHED'}

    def invoke(self, context, event):
        # sort types alphabetically
        component_registry.types = dict(sorted(component_registry.types.items(), key=lambda item: item[0]))
        wm = context.window_manager
        wm.invoke_search_popup(self)
        return {'FINISHED'}

    
    # def modal(self, context, event):
    #     if event.type == 'LEFTMOUSE':  # Confirm
    #         return {'FINISHED'}
    #     return {'RUNNING_MODAL'}

    # def draw(self, context):
    #     layout = self.layout
    #     # layout.prop(self, "filter", update=self.draw)
    #     # filterValue = self.filter
    #     for option in component_registry.types:
    #         if component_registry.isMissing(option):
    #             continue
    #         op = layout.operator("needle.addcomponent", text=option)
    #         op.displayName = option
    #         op.name = option


def openPopup():
    bpy.ops.wm.myop('INVOKE_DEFAULT')

# def register():
#     bpy.ops.wm.myop('INVOKE_DEFAULT')
    # bpy.utils.register_class(WM_OT_myop)

# def unregister():
#     bpy.utils.unregister_class(WM_OT_myop)

# if __name__ == "__main__":
#     register()
#     # test call
