import FreeCAD as App
import FreeCADGui as Gui

class PartCachedView:
	def __init__(self, direction, x_direction, obj):
		self.direction = direction
		self.x_direction = x_direction
		self.doc_name = obj.Document.Name
		self.obj_name = obj.Name
		self.cached_lines = None
		
	def render(self, in_doc):
		import numpy as np
		import os
		
		print("Rendering " + self.doc_name + "#" + self.obj_name + " in cache")
		
		workbench = Gui.getWorkbench("AssemblyHandbookWorkbench") #: :type workbench: AssemblyHandbookWorkbench
		
		doc = App.getDocument(self.doc_name) #: :type doc: App.Document
		obj = doc.getObject(self.obj_name) #: :type obj: App.DocumentObject
		
		# create temporary view
		page = in_doc.addObject('TechDraw::DrawPage', 'TmpPage')
		if not page.KeepUpdated: page.KeepUpdated = True
		template = in_doc.addObject('TechDraw::DrawSVGTemplate', 'Template')
		import ahb_locator
		template.Template = os.path.join(os.path.dirname(ahb_locator.__file__), "resources/A4_Landscape_blank.svg")
		page.Template = template
			
		tmpView = in_doc.addObject('TechDraw::DrawViewPart', 'TmpView')
		tmpView.ViewObject.Visibility = False
		tmpView.Direction = self.direction
		tmpView.XDirection = self.x_direction
		tmpView.Perspective = False
		tmpView.ScaleType = 'Custom'
		tmpView.Scale = 1.0
		tmpView.XSource = [obj]
		page.addView(tmpView)
		tmpView.recompute()
		
		# copy edges relative to center
		tmpCenter = workbench.techDrawExtensions.computePartCenter(tmpView, obj)
		
		# count lines
		tmpEdges = tmpView.getVisibleEdges()
		numLines = 0
		for edge in tmpEdges:
			if not hasattr(edge.Curve, 'Degree') or edge.Curve.Degree == 1: numLines += 1
		
		# store all lines in a packed array of floats (for each line: X1, Y1, X2, Y2)
		self.cached_lines = np.empty([numLines, 4])
		lineIdx = 0
		for edge in tmpEdges:
			if (not hasattr(edge.Curve, 'Degree') or edge.Curve.Degree == 1) and len(edge.Vertexes) == 2:
				sx = 1.0
				sy = -1.0
				self.cached_lines[lineIdx] = [
					edge.Vertexes[0].Point.x*sx - tmpCenter.x,
					edge.Vertexes[0].Point.y*sy - tmpCenter.y,
					edge.Vertexes[1].Point.x*sx - tmpCenter.x,
					edge.Vertexes[1].Point.y*sy - tmpCenter.y
				]
				lineIdx = lineIdx + 1
		
		# delete temporary view
		in_doc.removeObject(page.Name)

class PartsCache:
	part_views = {}
	
	def getPart2DView(self, view, obj):
		object_to_render = obj
		#if 'LinkedObject' in obj.PropertiesList:
		#	object_to_render = obj.LinkedObject
		obj_name = object_to_render.Document.Name + '#' + object_to_render.Name
		key = (view.Direction.x, view.Direction.y, view.Direction.z, view.XDirection.x, view.XDirection.y, view.XDirection.z, obj_name)
		part_view = self.part_views.get(key, None)
		if part_view is None:
			part_view = PartCachedView(view.Direction, view.XDirection, object_to_render)
			part_view.render(obj.Document)
			self.part_views[key] = part_view
		return part_view