# -*- coding: utf-8 -*-
# Makro: Exportiere_2D_DXF_LightBurn_Dialog
# Autor: ChatGPT (angepasst für FreeCAD 1.1.0)
# Funktion:
#   - Erstellt eine 2D-Projektion (Shape2DView) des ausgewählten PartDesign-Bodys
#   - Öffnet einen Dateidialog zum Speichern als DXF (R12-kompatibel)
#   - Exportiert saubere Konturen für LightBurn ohne doppelte Linien

import FreeCAD
import FreeCADGui
import Draft
import os
import time
from PySide import QtWidgets

doc = FreeCAD.ActiveDocument
if not doc:
    FreeCAD.Console.PrintError("⚠ Kein aktives Dokument gefunden.\n")
    raise SystemExit

sel = FreeCADGui.Selection.getSelection()
if not sel:
    FreeCAD.Console.PrintError("⚠ Kein Objekt ausgewählt. Bitte wähle den PartDesign-Body aus.\n")
    raise SystemExit

obj = sel[0]

# Prüfen, ob ein Body gewählt wurde
if not hasattr(obj, "TypeId") or "Body" not in obj.TypeId:
    FreeCAD.Console.PrintError("⚠ Bitte wähle im Modellbaum den PartDesign-Body aus (nicht eine Fläche oder Skizze).\n")
    raise SystemExit

# Shape2DView erzeugen
FreeCAD.Console.PrintMessage("🔄 Erzeuge 2D-Projektion aus: " + obj.Label + "\n")
shape2d = Draft.makeShape2DView(obj, FreeCAD.Vector(1,0,0))
shape2d.Label = obj.Label + "_2D"
doc.recompute()

# Dateidialog öffnen
dialog = QtWidgets.QFileDialog()
dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
dialog.setNameFilter("DXF-Dateien (*.dxf)")
dialog.setDefaultSuffix("dxf")
dialog.setWindowTitle("DXF für LightBurn speichern")
dialog.setDirectory(os.path.expanduser("~"))
dialog.selectFile(obj.Label + "_LightBurn.dxf")

if not dialog.exec():
    FreeCAD.Console.PrintMessage("❌ Export abgebrochen.\n")
    doc.removeObject(shape2d.Name)
    raise SystemExit

out_file = dialog.selectedFiles()[0]

# DXF-Export
try:
    FreeCAD.Console.PrintMessage("💾 Exportiere DXF nach: " + out_file + "\n")
    __objs__ = [shape2d]
    import importDXF
    importDXF.export(__objs__, out_file)
    del __objs__
    FreeCAD.Console.PrintMessage("✅ DXF-Export abgeschlossen.\n")
    FreeCAD.Console.PrintMessage("📁 Datei gespeichert unter: " + out_file + "\n")
finally:
    # Optional: 2D-Projektion wieder löschen (wenn nicht behalten werden soll)
    # doc.removeObject(shape2d.Name)
    FreeCADGui.SendMsgToActiveView("ViewFit")
