"""Bedienbefehle der Objektrahmen-Anzeige."""

import bpy
import os
import glob
import time
import math
import traceback

import gpu
import blf
from gpu_extras.batch import batch_for_shader
from bpy_extras.object_utils import world_to_camera_view
from bpy_extras import view3d_utils
from mathutils import Vector
from bpy.types import Panel, Operator, PropertyGroup, AddonPreferences
from bpy.props import (IntProperty, StringProperty, PointerProperty,
                       FloatProperty, BoolProperty, EnumProperty)

from . import state
from .draw_bbox import draw_bbox_callback
from .draw_labels import draw_bbox_labels_callback


# ============= PREDATOR HUD (TextTest Integration) - Operator-Klassen =============

class BBOX_OT_toggle_gpu_bbox(bpy.types.Operator):
    """Toggle viewport HUD with animated object tracking overlays and information labels"""
    bl_idname = "material.toggle_tracking"
    bl_label = "Toggle Object Tracking"
    bl_options = {'REGISTER'}
    
    _timer = None
    _is_running = False
    
    @classmethod
    def poll(cls, context):
        return context.space_data.type == 'VIEW_3D'
    
    def modal(self, context, event):
        # Mausposition bei JEDEM Event tracken
        if event.type == 'MOUSEMOVE':
            # Mausposition im Viewport (Region-Koordinaten)
            state._mouse_position = Vector((event.mouse_region_x, event.mouse_region_y))
        
        if event.type == 'TIMER':
            for area in context.screen.areas:
                if area.type == 'VIEW_3D':
                    area.tag_redraw()
        
        if not context.scene.basematerials_tracking:
            self.cancel(context)
            return {'CANCELLED'}
        
        return {'PASS_THROUGH'}
    
    def cancel(self, context):
        if self._timer:
            context.window_manager.event_timer_remove(self._timer)
            self._timer = None
        BBOX_OT_toggle_gpu_bbox._is_running = False
    
    def execute(self, context):
        scene = context.scene
        
        if state._bbox_handler is None:
            # Animation-Status, Cache und Sequenz zurücksetzen
            state._object_animations = {}
            state._cached_geometry_data = {}
            state._object_sequence = []
            state._sequence_index = 0
            state._animation_start_time = time.time()
            
            # Mausposition initialisieren (Viewport-Mitte)
            state._mouse_position = Vector((context.region.width // 2, context.region.height // 2))
            
            # Handler registrieren (POST_PIXEL für 2D!)
            state._bbox_handler = bpy.types.SpaceView3D.draw_handler_add(
                draw_bbox_callback, 
                (context,), 
                'WINDOW', 
                'POST_PIXEL'
            )
            
            # Labels aktivieren
            state._bbox_label_handler = bpy.types.SpaceView3D.draw_handler_add(
                draw_bbox_labels_callback,
                (context,),
                'WINDOW',
                'POST_PIXEL'
            )
            
            scene.basematerials_tracking = True
            
            # Modal-Operator mit 60 FPS
            if not BBOX_OT_toggle_gpu_bbox._is_running:
                self._timer = context.window_manager.event_timer_add(0.016, window=context.window)
                context.window_manager.modal_handler_add(self)
                BBOX_OT_toggle_gpu_bbox._is_running = True
                self.report({'INFO'}, "PREDATOR HUD aktiviert!")
                return {'RUNNING_MODAL'}
            
            self.report({'INFO'}, "HUD aktiviert")
        else:
            # Deaktivieren
            if state._bbox_handler:
                bpy.types.SpaceView3D.draw_handler_remove(state._bbox_handler, 'WINDOW')
                state._bbox_handler = None
            
            if state._bbox_label_handler:
                bpy.types.SpaceView3D.draw_handler_remove(state._bbox_label_handler, 'WINDOW')
                state._bbox_label_handler = None
            
            # Animation-Status, Cache und Sequenz löschen
            state._object_animations = {}
            state._cached_geometry_data = {}
            state._object_sequence = []
            state._sequence_index = 0
            
            scene.basematerials_tracking = False
            self.report({'INFO'}, "HUD deaktiviert")
        
        for area in context.screen.areas:
            if area.type == 'VIEW_3D':
                area.tag_redraw()
        
        return {'FINISHED'}


class BBOX_OT_update_gpu_bbox(bpy.types.Operator):
    """Manually refresh the object tracking overlay (updates automatically in realtime)"""
    bl_idname = "material.update_tracking"
    bl_label = "Update Tracking"
    bl_options = {'REGISTER'}
    
    @classmethod
    def poll(cls, context):
        return context.space_data.type == 'VIEW_3D' and context.scene.basematerials_tracking
    
    def execute(self, context):
        # Einstellungen werden live ausgelesen, kein Update nötig
        for area in context.screen.areas:
            if area.type == 'VIEW_3D':
                area.tag_redraw()
        
        self.report({'INFO'}, "Viewport aktualisiert")
        return {'FINISHED'}
