import FreeCAD
import FreeCADGui
from PySide2 import QtWidgets
import os

if FreeCAD.GuiUp:
    import FreeCADGui
    from PySide import QtCore, QtGui, QtWidgets
    from PySide.QtCore import QT_TRANSLATE_NOOP

    import os
else:
    # \cond
    def translate(ctxt, txt):
        return txt


    def QT_TRANSLATE_NOOP(ctxt, txt):
        return txt
    # \endcond

__title__ = "PVPlant Export to DXF"
__author__ = "Javier Braña"
__url__ = "http://www.sogos-solar.com"

from PVPlantResources import DirIcons as DirIcons


def copy_object_with_reference():
    try:
        # Verificar selección
        selected = FreeCADGui.Selection.getSelection()
        if len(selected) != 1:
            QtWidgets.QMessageBox.critical(None, "Error", "Selecciona exactamente un objeto")
            return

        original_doc = FreeCAD.ActiveDocument
        original_obj = selected[0]
        original_center = original_obj.Shape.BoundBox.Center

        # Crear nuevo documento
        new_doc = FreeCAD.newDocument(f"{original_doc.Name} - {original_obj.Label}")

        # Copiar objeto al nuevo documento
        new_obj = new_doc.copyObject(original_obj, True)
        new_obj.Label = f"Linked_{original_obj.Label}"
        new_obj.Placement.Base = original_obj.Placement.Base - original_center

        # Guardar el documenton nuevp
        path = os.path.dirname(FreeCAD.ActiveDocument.FileName)
        new_doc.saveAs(os.path.join(path, new_doc.Name))

        # Mantener posición original en el nuevo documento
        # new_obj.Placement = original_obj.Placement

        # Crear referencia (App::Link) en el documento original
        link = original_doc.addObject("App::Link", f"Link_{new_obj.Label}")
        link.LinkedObject = new_obj

        # Mantener posición original del objeto
        link.Placement = original_obj.Placement

        # Actualizar vistas
        original_doc.recompute()
        new_doc.recompute()

        # Regresar al documento original
        FreeCAD.setActiveDocument(original_doc.Name)

        #QtWidgets.QMessageBox.information(None, "Éxito", "Operación completada correctamente")

    except Exception as e:
        QtWidgets.QMessageBox.critical(None, "Error", f"Error: {str(e)}")


# Ejecutar la función
class CommandGenerateExternalDocument:
    def GetResources(self):
        return {'Pixmap': str(os.path.join(DirIcons, "dxf.svg")),
                'Accel': "P, E",
                'MenuText': "Export to DXF",
                'ToolTip': QT_TRANSLATE_NOOP("Placement", "Export choosed layers to dxf")}

    def Activated(self):
        ''' '''
        copy_object_with_reference()

    def IsActive(self):
        if FreeCAD.ActiveDocument:
            return True
        else:
            return False