from imgui_bundle import imgui, imgui_ctx


class InteractionPanels:
    """Drag-and-drop and context menu interaction panels."""

    def __init__(self, app):
        self.app = app

    def __getattr__(self, name):
        return getattr(self.app, name)

    def __setattr__(self, name, value):
        if name == "app" or name in self.__dict__ or hasattr(type(self), name):
            object.__setattr__(self, name, value)
        else:
            setattr(self.app, name, value)


    def _draw_drag_drop_interface(self):
        """委托到核心拖拽服务。"""
        return self.model_drag_drop.draw_drag_drop_interface()


    def _handle_drag_drop_completion(self):
        """委托到核心拖拽服务。"""
        return self.model_drag_drop.handle_internal_drag_drop_completion()


    def _draw_drag_overlay(self):
        return self.model_drag_drop.draw_drag_overlay()


    def _draw_drag_status(self):
        return self.model_drag_drop.draw_drag_status()
    

    def _draw_context_menus(self):
        """绘制右键菜单"""
        # 节点右键菜单
        if hasattr(self, '_context_menu_node') and self._context_menu_node:
            imgui.open_popup("节点右键菜单")
            self._context_menu_node = None
        
        if imgui.begin_popup("节点右键菜单"):
            if imgui.menu_item("删除节点", "", False, True)[1]:
                if hasattr(self, '_context_menu_target') and self._context_menu_target:
                    self._delete_node(self._context_menu_target)
                imgui.close_current_popup()
            
            if imgui.menu_item("重命名", "", False, True)[1]:
                self._renaming_node = True
                imgui.close_current_popup()
            
            imgui.separator()
            
            if imgui.menu_item("复制", "", False, True)[1]:
                if hasattr(self, '_context_menu_target') and self._context_menu_target:
                    self._copy_node(self._context_menu_target)
                imgui.close_current_popup()
            
            if imgui.menu_item("聚焦", "", False, True)[1]:
                if hasattr(self, '_context_menu_target') and self._context_menu_target:
                    if hasattr(self, 'selection') and self.selection:
                        self.selection.updateSelection(self._context_menu_target)
                        self.selection.focusCameraOnSelectedNodeAdvanced()
                imgui.close_current_popup()
            
            imgui.end_popup()
        
        # 重命名对话框
        if hasattr(self, '_renaming_node') and self._renaming_node:
            imgui.open_popup("重命名节点")
            if not hasattr(self, '_rename_buffer'):
                self._rename_buffer = ""
                if hasattr(self, '_context_menu_target') and self._context_menu_target:
                    self._rename_buffer = self._context_menu_target.getName() or ""
        
        if imgui.begin_popup("重命名节点"):
            changed, new_name = imgui.input_text("新名称", self._rename_buffer, 256)
            if changed:
                self._rename_buffer = new_name
            
            if imgui.button("确定"):
                if hasattr(self, '_context_menu_target') and self._context_menu_target:
                    self._context_menu_target.setName(self._rename_buffer)
                self._renaming_node = False
                imgui.close_current_popup()
            
            imgui.same_line()
            if imgui.button("取消"):
                self._renaming_node = False
                imgui.close_current_popup()
            
            imgui.end_popup()
    

    def _delete_node_simple(self, node):
        """删除节点 - 简化版本"""
        if not node or node.isEmpty():
            return
        
        # 从场景管理器中删除
        if hasattr(self, 'scene_manager') and self.scene_manager:
            if hasattr(self.scene_manager, 'models') and node in self.scene_manager.models:
                self.scene_manager.models.remove(node)
        
        # 从GUI管理器中删除
        if hasattr(self, 'gui_manager') and self.gui_manager:
            gui_element = None
            if hasattr(node, 'getPythonTag'):
                gui_element = node.getPythonTag('gui_element')
            if gui_element and hasattr(self.gui_manager, 'gui_elements'):
                if gui_element in self.gui_manager.gui_elements:
                    self.gui_manager.gui_elements.remove(gui_element)
        
        # 使用主删除方法
        self._delete_node(node)
        
        # 获取节点名称（在删除之前）
        node_name = node.getName() if not node.isEmpty() else '未命名节点'
        
        # 删除节点本身
        node.removeNode()
        
        # 清除选择
        if hasattr(self, 'selection') and self.selection:
            if self.selection.selectedNode == node:
                self.selection.clearSelection()
        
        # 添加成功消息
        self.add_success_message(f"已删除节点: {node_name}")
    

    def _copy_node(self, node):
        """复制节点"""
        if not node or node.isEmpty():
            return
        
        # 这里可以实现节点复制逻辑
        # 暂时只显示消息
        self.add_info_message(f"复制功能暂未实现: {node.getName() or '未命名节点'}")
    
    # ==================== 创建功能实现 ====================
