
import bpy
from .panels_components import CustomPropertyType

def resolvePath(obj, key, path:str):
    obj = getattr(obj, key)
    sections = path.split("/")
    for section in sections:
        if section == "":
            continue
        obj = getattr(obj, section)
    return obj


class addListItemOp(bpy.types.Operator):
    bl_idname = "component.add_item"
    bl_label = "Add"
    bl_options = {"REGISTER"}
    bl_description = "TODO"

    key: bpy.props.StringProperty(name="Key", default="")
    path: bpy.props.StringProperty(name="PropName", default="")

    def execute(self, context):
        list = resolvePath(context.object, self.key, self.path)
        newEntry = list.add()
        return {"FINISHED"}


class removeListItemOp(bpy.types.Operator):
    bl_idname = "component.remove_item"
    bl_label = "Remove"
    bl_options = {"REGISTER"}
    bl_description = "TODO"

    key: bpy.props.StringProperty(name="Key", default="")
    path: bpy.props.StringProperty(name="PropName", default="")
    index: bpy.props.IntProperty(name="Index")

    def execute(self, context):
        list = resolvePath(context.object, self.key, self.path)
        list.remove(self.index)
        # context.active_object.list_index = min(max(0, index - 1), len(alist) - 1)
        # context.area.tag_redraw()
        return {"FINISHED"}

class clearListOp(bpy.types.Operator):
    bl_idname = "component.clear_list"
    bl_label = "Clear"
    bl_options = {"REGISTER"}
    bl_description = "TODO"

    key: bpy.props.StringProperty(name="Key", default="")
    path: bpy.props.StringProperty(name="PropName", default="")

    def execute(self, context):
        list = resolvePath(context.object, self.key, self.path)
        list.clear()
        return {"FINISHED"}