import importSVG
import Draft

outputRacine = App.activeDocument().getFileName().rpartition('.')[0]

# -------- REPRISE DE LA MACRO "exportSketchEnMasse-SVG" de Gauthier Brière -------- #

def exportSketch():
	for __O__ in App.ActiveDocument.findObjects('Sketcher::SketchObject'):
		__obj__ = []
		__obj__.append(__O__)

		print('Export SVG de : ' + __obj__[0].Label)

		oldPlace  = __obj__[0].Placement
		__obj__[0].Placement=App.Placement(App.Vector(0,0,0), App.Rotation(App.Vector(1,0,0),0), App.Vector(0,0,0))
		fichierSVG = u"" + outputRacine + '--' + __obj__[0].Label + '.svg'
		importSVG.export(__obj__, fichierSVG)
		__obj__[0].Placement = oldPlace
	
	App.activeDocument().recompute()

# -------- END -------- #

sketchList = []

for selectedObject in Gui.Selection.getSelectionEx():
	foundX = False
	foundY = False
	foundZ = False

	for child in selectedObject.Object.Objects:
		if hasattr(child, 'Start') and hasattr(child, 'End'):
			if (foundX and foundY) or (foundY and foundZ) or (foundZ and foundX):
				break
	
			if (child.Start.x != 0.0 and child.Start.x != -0.0) or (child.End.x != 0.0 and child.End.x != -0.0):
				foundX = True
			if (child.Start.y != 0.0 and child.Start.y != -0.0) or (child.End.y != 0.0 and child.End.y != -0.0):
				foundY = True
			if (child.Start.z != 0.0 and child.Start.z != -0.0) or (child.End.z != 0.0 and child.End.z != -0.0):
				foundZ = True
	
	vector = FreeCAD.Vector(1.0, 0.0, 0.0)
	if foundX and foundY and not foundZ:
		vector = FreeCAD.Vector(0.0, 0.0, 1.0)
	if foundX and foundZ and not foundY:
		vector = FreeCAD.Vector(0.0, 1.0, 0.0)

	sv0 = Draft.make_shape2dview(selectedObject.Object, vector)
	FreeCAD.ActiveDocument.recompute()
	sk = Draft.make_sketch(sv0, autoconstraints=True)
	sketchList.append(sk)	

	FreeCAD.ActiveDocument.recompute()
	App.ActiveDocument.removeObject(sv0.Name)

exportSketch()

for skObject in sketchList:
	App.ActiveDocument.removeObject(skObject.Name)

FreeCAD.ActiveDocument.recompute()