
import bpy
from .bl_utils import get_mat, get_collection_parents


def get_picker_collection(ob=None):
    """Return the picker collection of an object"""

    if not ob:
        ob = bpy.context.object

    for col in ob.users_collection:
        if col.rig_picker.enabled:
            return col
            
        if picker_col := next((c for c in get_collection_parents(col) if c.rig_picker.enabled), None):
            return picker_col


def is_shape(ob):
    scn = bpy.context.scene
    canvas = scn.rig_picker.canvas
    if not canvas or ob.hide_render:
        return False
    
    shapes = {ob for col in canvas.users_collection for ob in col.all_objects}

    if ob.type in ('MESH', 'CURVE', 'FONT') and ob in shapes:
        return True

    return False


def get_object_color(ob):
    if not ob.data.materials:
        return
    
    mat = get_mat(ob)
    if not mat or not mat.node_tree or not mat.node_tree.nodes:
        return

    emit_node = mat.node_tree.nodes.get('Emission')
    if not emit_node:
        return
    
    return emit_node.inputs['Color'].default_value


def get_operator_from_id(idname):
    if not '.' in idname:
        return

    m, o = idname.split(".")
    try:
        op = getattr(getattr(bpy.ops, m), o)
        op.get_rna_type()
    except Exception:
        return
    
    return op