import bpy
from .extensions.NEEDLE_gameobject_data import getDefaultLayerName
from .utils_icons import getPreviewIcon


def applyLightmapSettingsToAllSelectedObjects(self, context):
    isLightmappedSetting = self.NEEDLE_isLightmapped
    lightmapScale = self.NEEDLE_lightmapScale
    bpy.app.timers.register(lambda:__applyIsLightmappedToAllSelectedObjectDelayed(self, context, isLightmappedSetting, lightmapScale), first_interval=0)
isApplyingLightmappingSettings = False
def __applyIsLightmappedToAllSelectedObjectDelayed(self, context, isLightmappedSetting, lightmapScale):
    global isApplyingLightmappingSettings
    if isApplyingLightmappingSettings:
        return
    isApplyingLightmappingSettings = True
    try:
        for obj in context.selected_objects:
            if obj == self:
                continue
            print("Setting lightmapped to " + str(isLightmappedSetting) + " for " + obj.name)
            if obj.NEEDLE_isLightmapped != isLightmappedSetting:
                obj.NEEDLE_isLightmapped = isLightmappedSetting
            if obj.NEEDLE_lightmapScale != lightmapScale:
                obj.NEEDLE_lightmapScale = lightmapScale
    finally:
        isApplyingLightmappingSettings = False



def register():
    bpy.types.Object.NEEDLE_isLightmapped = bpy.props.BoolProperty(name="Lightmapped", default=False, update=applyLightmapSettingsToAllSelectedObjects)
    bpy.types.Object.NEEDLE_lightmapScale = bpy.props.FloatProperty(
        name="Lightmap Scale Factor",
        description="Increase to give this object more space in the lightmap texture (more resolution/better quality) - decrease to reduce the space it takes up (giving more texture space to other lightmapped objects)",
        default=1.0,
        min=0.01,
        max=100,
        update=applyLightmapSettingsToAllSelectedObjects,
    )
    bpy.types.Material.NEEDLE_useInstancing = bpy.props.BoolProperty(name="Instancing", default=False)
    pass

def unregister():
    del bpy.types.Object.NEEDLE_isLightmapped
    del bpy.types.Material.NEEDLE_useInstancing
    del bpy.types.Object.NEEDLE_lightmapScale
    pass

# def applyIsInstancedToAllSelectedObject(self, context):
#     isInstancedSetting = self.NEEDLE_useInstancing
#     selectedObjects = context.selected_objects
#     bpy.app.timers.register(lambda:__applyUsingInstancing(self, selectedObjects, isInstancedSetting), first_interval=3)
# isChangingInstancingSetting = False
# def __applyUsingInstancing(self, selectedObjects, value):
#     global isChangingInstancingSetting
#     if isChangingInstancingSetting: 
#         return
#     isChangingInstancingSetting = True
#     try:
#         for obj in selectedObjects:
#             if obj.type == "Mesh" and obj.active_material:
#                 material = obj.active_material
#                 if material == self:
#                     continue
#                 if material.NEEDLE_useInstancing == value:
#                     continue
#                 print("Setting instanced to " + str(value) + " for " + obj.name)
#                 material.NEEDLE_useInstancing = value
#     finally:
#         isChangingInstancingSetting = False


def hasInstancingEnabled(blender_object) -> bool:
    if blender_object.type != "MESH":
        return False
    activeMaterial = blender_object.active_material
    if activeMaterial is None:
        return False
    if not activeMaterial.NEEDLE_useInstancing:
        return False
    return True

def drawInstancingOptions(material:bpy.types.Material, layout:bpy.types.UILayout):
    layout.prop(material, "NEEDLE_useInstancing", text="Use Instancing")


class ObjectPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_idname = "OBJECT_PT_NEEDLE_object"
    bl_label = "Needle Object"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

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

    def draw(self, context):
        layout = self.layout
        obj = context.object

        object_properties = obj.NEEDLE_gameobject_data
        if object_properties is not None:
            splitFactor = .4

            # if the object is the camera
            if obj.type == "CAMERA":
                layout.prop(object_properties, "isMainCamera", text="Main Camera")

            tagRow = layout.split(factor=splitFactor)
            tagRow.label(text="Tag:") 
            tagRow.prop(object_properties, "tag", text="")

            if obj.type == "CAMERA" and object_properties.isMainCamera:
                tagRow.enabled = False



            layerRow = layout.split(factor=splitFactor)
            layerName = getDefaultLayerName(object_properties.layer)
            if layerName:
                layerRow.label(text="Layer: " + layerName) 
            else:
                layerRow.label(text="Layer: " + str(object_properties.layer))
            layerRow.prop(object_properties, "layer", text="Layer")
        # if obj.type == "MESH":
        #     activeMaterial = obj.active_material
        #     if activeMaterial is None:
        #         layout.label(text="Object requires material to be lightmapped", icon="ERROR")
        #         layout = layout.column(align=True)
        #         layout.enabled = False
        lightmapSplit = layout.split(factor=0.4)
        lightmapSplit.prop(obj, "NEEDLE_isLightmapped", text="Lightmapped")

        if obj.type == "MESH":

            lightmapOptions = lightmapSplit.row(align=True)
            lightmapOptions.enabled = obj.NEEDLE_isLightmapped
            lightmapOptions.prop(obj, "NEEDLE_lightmapScale", text="Lightmap Scale Factor")

            material = obj.active_material
            if material is not None:
                drawInstancingOptions(material, layout)
            else:
                row = layout.row(align=True)
                row.label(text="Object requires material to be instanced", icon="ERROR")
                buttonlayout = row.column(align=True)
                buttonlayout.scale_x = 0.5
                buttonlayout.operator("needle.assign_default_material", text="Assign", icon="MATERIAL_DATA")
        # row = layout.row(align=True)
        # previewLightmap = row.operator("needle.bake_lightmaps", text="Preview Scene Lightmaps")
        # previewLightmap.preview = True
        # qualityLightmap = row.operator("needle.bake_lightmaps", text="Bake Scene Lightmaps")
        # qualityLightmap.preview = False

