import bpy
from .panels_object import drawInstancingOptions
from .image_types import drawImageSettings
from .utils_icons import getPreviewIcon


class MaterialPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_idname = "OBJECT_PT_NEEDLE_material_settings"
    bl_label = "Needle Material Settings"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "material"

    def draw_header(self, context):
        layout = self.layout
        icon = getPreviewIcon("logo_small_bw")
        layout.label(text="", icon_value=icon)

    @classmethod
    def poll(self, context):
        return context.object.active_material is not None

    def draw(self, context):
        layout = self.layout
        obj = context.object
        active_material = obj.active_material
        if active_material is None:
            return
        # iterate textures
        tree = active_material.node_tree
        if tree is None:
            return
        
        layout.label(text="Material Settings", icon="MATERIAL")    
        drawInstancingOptions(active_material, layout)

        layout.separator()

        headerRow = layout.split(factor=0.7)
        headerRow.label(text="Texture Compression Settings", icon="TEXTURE")
        headerRow.operator("needle.open_url", text="Learn More", icon="QUESTION").url = "https://fwd.needle.tools/needle-engine/docs/compression"

        imageSlots: dict = {}
        for node in tree.nodes:
            if node.type != "TEX_IMAGE":
                # layout.label(text=node.name)
                continue
            image = node.image
            if image is None:
                layout.label(text=node.name)
                continue
            
            # layout.label(text=node.image.name, icon="IMAGE_DATA")
            if image.name_full in imageSlots:
                imageSlots[image.name_full]["slots"].append(node.label)
            else:
                imageSlots[image.name_full] = {
                    "image": image,
                    "slots": [node.label],
                }

        didDrawImageSettings = False
        for [_, value] in imageSlots.items():
            didDrawImageSettings = True
            slots = value["slots"]
            image = value["image"]
            drawImageSettings(self, image, slots)

        if not didDrawImageSettings:
            layout.label(text="Texture compression settings will be displayed here. This material has no textures.")
            

        
