import bpy
from .utils import showMessage
from .extensions.NEEDLE_components_unknown import UnknownPointerObject


class NEEDLE_PT_ComponentUnknown(bpy.types.Panel):
    bl_label = "Needle → Unknown Components"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"
    bl_description = "Components that blender does not know how to deserialize"

    def draw_header(self, context):
        layout = self.layout
        layout.label(text="", icon='UNLINKED')

    @classmethod
    def poll(self, context):
        if not hasattr(context.object, "NEEDLE_unknown_components"):
            return False
        col = getattr(context.object, "NEEDLE_unknown_components")
        return len(col) > 0

    def draw(self, context):
        if not hasattr(context.object, "NEEDLE_unknown_components"):
            return
        col = getattr(context.object, "NEEDLE_unknown_components")
        root_layout = self.layout
        count = len(col)
        if count <= 0:
            row = root_layout.row(align=True)
            row.enabled = False
            row.label(text="> No unknown components found")
            return
        for i in range(count):
            item = col[i]
            layout = root_layout.box()
            headline = layout.row(align=True)
            headline.label(text=item.name)
            jsonLayout = headline.column(align=True)
            jsonLayout.alignment = 'EXPAND'
            jsonLayout.enabled = False
            jsonLayout.prop(item, "json", text="")
            headline.operator("needle.copy_json", text="", icon='COPYDOWN').json = item.json
            # headline.operator("needle.show_message_box", text="", icon='INFO').message = item.json
            for reference in item.references:
                if isinstance(reference, UnknownPointerObject):
                    reference.draw(context, layout)
            # self.layout.prop(el, "json", text="")
        pass


# copy json operator
class NEEDLE_OT_CopyJson(bpy.types.Operator):
    bl_idname = "needle.copy_json"
    bl_label = "Copy Json"
    bl_description = "Copy the json of this component to the clipboard"

    json: bpy.props.StringProperty()

    def execute(self, context):
        bpy.context.window_manager.clipboard = self.json
        showMessage("copied to clipboard", "json", 'COPYDOWN')
        return {'FINISHED'}
        



def register():
    unregister()
    bpy.utils.register_class(NEEDLE_PT_ComponentUnknown)
    pass

def unregister():
    bpy.utils.unregister_class(NEEDLE_PT_ComponentUnknown)
    pass