#######################################################################################################################################################
# This module writes GCode toolpath files                                                                                                               #
#######################################################################################################################################################
"""
Licensed under GPL v2 and the 'I'm not going to help you kill people licence'. The latter overrules the former.
        
I'm not going to help you kill people licence v1.1:
The use of this software in any form for any purposes relating to any form of military activity or
research either directly or via subcontracts is strictly prohibited.
Any company or organisation affiliated with any military organisations either directly or through
subcontracts are strictly prohibited from using any part of this software.
Individuals who work for the above mentioned organisations working on PERSONAL or open source projects unrelated
to above mentioned organisations in their own time may use this software.

GNU licence:        
RepRap Gerber Plotter is free software; you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the Free Software Foundation; 
either version 2 of the License, or (at your option) any later version.

RepRap Gerber Plotter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
See the GNU General Public License for more details. You should have received a copy of 
the GNU General Public License along with File Hunter; if not, write to 
the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

import replath.preferences, replath.baseplotters
import reprap	#remove?
#from gcode_prefpanel import PreferencesPanel

Title = "GCode File"
FileOutput = True
Wildcard = 'GCode files (*.gcode)|*.gcode'

class output(replath.baseplotters.ExportPlotter):
	# Load plotter preferences
	def loadPreferences(self):
		self.prefHandler = replath.preferences.PreferenceHandler(self,  "output_gcode.conf")
		self.prefHandler.load()
	
	# Start plot (as new thread)
	def run(self):
		self.alive = True
		self.gcode = GCode()
		self.curZ = 0
		
		for layer in self.toolpath.layers:
			x2, y2 = self.toolpath.offsetX, self.toolpath.offsetY
			for polygon in layer.polygons:
				if not self.alive:
					self.feedbackHandler.aborted()
					break
				
				x1, y1 = polygon.points[0].x + self.toolpath.offsetX, polygon.points[0].y + self.toolpath.offsetY
				# If we are not in the polygon start place, switch off tool and move there
				if (x1 != x2) or (y1 != y2):
					self.toolhead.stop()
					self.cartesianMove(x1, y1, None)
				# Start tool
				self.toolhead.start()
				# Plot polygon
				for point in polygon.points[ 1: ]:
					x2, y2 = point.x + self.toolpath.offsetX, point.y + self.toolpath.offsetY
					# If we need to move somwhere, do it
					if (x1 != x2) or (y1 != y2):
						self.cartesianMove(x2, y2, None)
				x1, y1 = x2, y2
			
		# Stop tool and write file
		self.toolhead.stop()
		self.gcode.writeFile(self.outputFilename)
		
		if self.alive:
			# Tell gui that plot is complete (redraw screen)
			self.feedbackHandler.plotComplete()
	
	# Translate a cartesian movement into whatever the output plugin does with it (called locally and by toolhead)
	def cartesianMove(self, x, y, z, units = reprap.UNITS_MM):
		self.gcode.addCoordinate( x, y, z )
		# TODO, get toolhead working in mm?
		# TODO, should we round coordinates


# Class for gcode file
class GCode():
	def __init__(self):
		self.coordinates = []
	
	def addCoordinate(self, x, y, z):
		self.coordinates.append ( (x, y, z) )
	
	def generateGCode(self):
		gcode = "(GCode generated by RepRap Plot)\nG21 (Millimeters)\nG28 (Go Home)\nG90 (Absolute Positioning)\n(Start Plot)\n"
		for x, y, z in self.coordinates:
			if z == None:
				gcode += 'G1 X' + str(x) + ' Y' + str(y) + '\n'
			else:
				gcode += 'G1 Z' + str(z) + '\n'
		gcode += "G28 (Go Home)"
		return gcode
	
	def writeFile(self, fileName):
		gcode = self.generateGCode()
		f = open( fileName, 'w' )
		f.write(gcode)
		f.close()


