import bpy
from ...utils import generateRandomStringId


class setDefaultStateOp(bpy.types.Operator):
    bl_idname = "needle_animator.set_default_state"
    bl_label = "Set default state"
    bl_description = "Set animator default state"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        node = context.active_node
        tree = context.space_data.node_tree
        if node and tree:
            tree.setDefaultState(node.state_id)
            context.area.tag_redraw()

        return {'FINISHED'}


class addTransitionOp(bpy.types.Operator):
    bl_idname = "needle_animator.add_transition"
    bl_label = "Add Transition"
    bl_description = "Add Transition"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        node = context.active_node
        transition = node.transitions.add()
        transition.name = "Transition " + str(len(node.transitions))
        transition.transitionId = "animator_transition_" + generateRandomStringId(10)
        node.onTransitionAdded(transition)
        return {'FINISHED'}

class removeTransitionOp(bpy.types.Operator):
    bl_idname = "needle_animator.remove_transition"
    bl_label = "Remove Transition"
    bl_description = "Remove Transition"
    bl_options = {'REGISTER', 'UNDO'}

    transitionId: bpy.props.StringProperty()

    def execute(self, context):
        node = context.active_node
        for i in range(len(node.transitions)):
            transition = node.transitions[i]
            if transition.transitionId == self.transitionId:
                node.transitions.remove(i)
                node.onTransitionRemoved(self.transitionId)
                break
        return {'FINISHED'}

def register():
    bpy.utils.register_class(setDefaultStateOp)
    bpy.utils.register_class(addTransitionOp)
    bpy.utils.register_class(removeTransitionOp)

def unregister():
    bpy.utils.unregister_class(setDefaultStateOp)
    bpy.utils.unregister_class(addTransitionOp)
    bpy.utils.unregister_class(removeTransitionOp)