"""
Multiply is a script to multiply the shape into an array of copies arranged in a table.

The default 'Activate Multiply' checkbox is on.  When it is on, the functions described below will work, when it is off, the
functions will not be called.  The multiply script sets the feedrate, and flowrate.  To run multiply, in a shell type:
> python multiply.py

The center of the shape will be moved to the "Center X" and "Center Y" coordinates.

The "Number of Columns" preference is the number of columns in the array table.  The "Number of Rows" is the number of rows
in the table.  The "Separation over Extrusion Width" is the ratio of separation between the shape copies over the extrusion width.

Besides using the multiply tool, another way of printing many copies of the model is to duplicate the model in Art of Illusion,
however many times you want, with the appropriate offsets.  Then you can either use the Join Objects script in the scripts
submenu to create a combined shape or you can export the whole scene as an xml file, which skeinforge can then slice.

The following examples multiply the files Screw Holder Bottom.gcode & Screw Holder Bottom.stl.  The examples are run in a
terminal in the folder which contains Screw Holder Bottom.gcode, Screw Holder Bottom.stl and multiply.py.  The multiply
function will multiply if "Activate Multiply" is true, which can be set in the dialog or by changing the preferences file
'multiply.csv' with a text editor or a spreadsheet program set to separate tabs.  The functions writeOutput and
getMultiplyChainGcode check to see if the text has been multiplied, if not they call getFillChainGcode in fill.py to get filled
gcode; once they have the filled text, then they multiply.


> python multiply.py
This brings up the dialog, after clicking 'Multiply', the following is printed:
File Screw Holder Bottom.stl is being chain multiplied.
The multiplied file is saved as Screw Holder Bottom_multiply.gcode


>python
Python 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import multiply
>>> multiply.main()
This brings up the multiply dialog.


>>> multiply.writeOutput()
Screw Holder Bottom.stl
File Screw Holder Bottom.stl is being chain multiplied.
The multiplied file is saved as Screw Holder Bottom_multiply.gcode


>>> multiply.getMultiplyGcode("
( GCode generated by May 8, 2008 carve.py )
( Extruder Initialization )
..
many lines of gcode
..
")


>>> multiply.getMultiplyChainGcode("
( GCode generated by May 8, 2008 carve.py )
( Extruder Initialization )
..
many lines of gcode
..
")

"""


from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__

from skeinforge_tools.skeinforge_utilities import euclidean
from skeinforge_tools.skeinforge_utilities import gcodec
from skeinforge_tools.skeinforge_utilities import intercircle
from skeinforge_tools.skeinforge_utilities import preferences
from skeinforge_tools import analyze
from skeinforge_tools import fill
from skeinforge_tools.skeinforge_utilities import interpret
from skeinforge_tools import material
from skeinforge_tools import polyfile
import cStringIO
import math
import sys
import time


__author__ = "Enrique Perez (perez_enrique@yahoo.com)"
__date__ = "$Date: 2008/21/04 $"
__license__ = "GPL 3.0"


def getMultiplyChainGcode( fileName, gcodeText, multiplyPreferences = None ):
	"Multiply a gcode linear move text.  Chain multiply the gcode if it is not already multiplied."
	gcodeText = gcodec.getGcodeFileText( fileName, gcodeText )
	if not gcodec.isProcedureDone( gcodeText, 'fill' ):
		gcodeText = fill.getFillChainGcode( fileName, gcodeText )
	return getMultiplyGcode( gcodeText, multiplyPreferences )

def getMultiplyGcode( gcodeText, multiplyPreferences = None ):
	"Multiply a gcode linear move text."
	if gcodeText == '':
		return ''
	if gcodec.isProcedureDone( gcodeText, 'multiply' ):
		return gcodeText
	if multiplyPreferences == None:
		multiplyPreferences = MultiplyPreferences()
		preferences.readPreferences( multiplyPreferences )
	if not multiplyPreferences.activateMultiply.value:
		return gcodeText
	skein = MultiplySkein()
	skein.parseGcode( gcodeText, multiplyPreferences )
	return skein.output.getvalue()

def writeOutput( fileName = '' ):
	"""Multiply a gcode linear move file.  Chain multiply the gcode if it is not already multiplied.
	If no fileName is specified, multiply the first unmodified gcode file in this folder."""
	if fileName == '':
		unmodified = interpret.getGNUTranslatorFilesUnmodified()
		if len( unmodified ) == 0:
			print( "There are no unmodified gcode files in this folder." )
			return
		fileName = unmodified[ 0 ]
	multiplyPreferences = MultiplyPreferences()
	preferences.readPreferences( multiplyPreferences )
	startTime = time.time()
	print( 'File ' + gcodec.getSummarizedFilename( fileName ) + ' is being chain multiplied.' )
	suffixFilename = fileName[ : fileName.rfind( '.' ) ] + '_multiply.gcode'
	multiplyGcode = getMultiplyChainGcode( fileName, '', multiplyPreferences )
	if multiplyGcode == '':
		return
	gcodec.writeFileText( suffixFilename, multiplyGcode )
	print( 'The multiplied file is saved as ' + gcodec.getSummarizedFilename( suffixFilename ) )
	analyze.writeOutput( suffixFilename, multiplyGcode )
	print( 'It took ' + str( int( round( time.time() - startTime ) ) ) + ' seconds to multiply the file.' )


class MultiplyPreferences:
	"A class to handle the multiply preferences."
	def __init__( self ):
		"Set the default preferences, execute title & preferences fileName."
		#Set the default preferences.
		self.archive = []
		self.activateMultiply = preferences.BooleanPreference().getFromValue( 'Activate Multiply:', False )
		self.archive.append( self.activateMultiply )
		self.centerX = preferences.FloatPreference().getFromValue( 'Center X (millimeters):', 0.0 )
		self.archive.append( self.centerX )
		self.centerY = preferences.FloatPreference().getFromValue( 'Center Y (millimeters):', 0.0 )
		self.archive.append( self.centerY )
		self.fileNameInput = preferences.Filename().getFromFilename( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File to be Multiplied', '' )
		self.archive.append( self.fileNameInput )
		self.numberOfColumns = preferences.IntPreference().getFromValue( 'Number of Columns (integer):', 1 )
		self.archive.append( self.numberOfColumns )
		self.numberOfRows = preferences.IntPreference().getFromValue( 'Number of Rows (integer):', 1 )
		self.archive.append( self.numberOfRows )
		self.separationOverExtrusionWidth = preferences.FloatPreference().getFromValue( 'Separation over Extrusion Width (ratio):', 15.0 )
		self.archive.append( self.separationOverExtrusionWidth )
		#Create the archive, title of the execute button, title of the dialog & preferences fileName.
		self.executeTitle = 'Multiply'
		self.saveTitle = 'Save Preferences'
		preferences.setHelpPreferencesFileNameTitleWindowPosition( self, 'skeinforge_tools.multiply.html' )

	def execute( self ):
		"Multiply button has been clicked."
		fileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFilenames(), self.fileNameInput.wasCancelled )
		for fileName in fileNames:
			writeOutput( fileName )


class MultiplySkein:
	"A class to multiply a skein of extrusions."
	def __init__( self ):
		self.decimalPlacesCarried = 3
		self.layerIndex = 0
		self.layerLines = []
		self.lineIndex = 0
		self.lines = None
		self.oldLocation = None
		self.output = cStringIO.StringIO()
		self.rowIndex = 0
		self.shouldAccumulate = True

	def addElement( self, offset ):
		"Add moved element to the output."
		for line in self.layerLines:
			splitLine = line.split()
			firstWord = gcodec.getFirstWord( splitLine )
			if firstWord == 'G1':
				movedLocation = self.getMovedLocationSetOldLocation( offset, splitLine )
				line = self.getGcodeFromMovementZ( movedLocation, self.oldLocation.z )
			elif firstWord == '(<boundaryPoint>':
				movedLocation = self.getMovedLocationSetOldLocation( offset, splitLine )
				line = '(<boundaryPoint> X%s Y%s Z%s )' % ( self.getRounded( movedLocation.real ), self.getRounded( movedLocation.imag ), self.getRounded( self.oldLocation.z ) )
			self.addLine( line )

	def addLayer( self ):
		"Add multiplied layer to the output."
		offset = self.centerOffset - self.arrayCenter - self.shapeCenter
		for rowIndex in xrange( self.multiplyPreferences.numberOfRows.value ):
			yRowOffset = float( rowIndex ) * self.extentPlusSeparation.imag
			if self.layerIndex % 2 == 1:
				yRowOffset = self.arrayExtent.imag - yRowOffset
			for columnIndex in xrange( self.multiplyPreferences.numberOfColumns.value ):
				xColumnOffset = float( columnIndex ) * self.extentPlusSeparation.real
				if self.rowIndex % 2 == 1:
					xColumnOffset = self.arrayExtent.real - xColumnOffset
				elementOffset = complex( offset.real + xColumnOffset, offset.imag + yRowOffset )
				self.addElement( elementOffset )
			self.rowIndex += 1
		if len( self.layerLines ) > 1:
			self.layerIndex += 1
		self.layerLines = []

	def addLine( self, line ):
		"Add a line of text and a newline to the output."
		if len( line ) > 0:
			self.output.write( line + "\n" )

	def getGcodeFromMovementZ( self, point, z ):
		"Get a gcode movement."
		return "G1 X%s Y%s Z%s" % ( self.getRounded( point.real ), self.getRounded( point.imag ), self.getRounded( z ) )

	def getMovedLocationSetOldLocation( self, offset, splitLine ):
		"Get the moved location and set the old location."
		location = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )
		self.oldLocation = location
		return location.dropAxis( 2 ) + offset

	def getRounded( self, number ):
		"Get number rounded to the number of carried decimal places as a string."
		return euclidean.getRoundedToDecimalPlacesString( self.decimalPlacesCarried, number )

	def parseGcode( self, gcodeText, multiplyPreferences ):
		"Parse gcode text and store the multiply gcode."
		self.centerOffset = complex( multiplyPreferences.centerX.value, multiplyPreferences.centerY.value )
		self.multiplyPreferences = multiplyPreferences
		self.numberOfColumns = multiplyPreferences.numberOfColumns.value
		self.numberOfRows = multiplyPreferences.numberOfRows.value
		self.lines = gcodec.getTextLines( gcodeText )
		self.parseInitialization()
		self.setCorners()
		for line in self.lines[ self.lineIndex : ]:
			self.parseLine( line )

	def parseInitialization( self ):
		"Parse gcode initialization and store the parameters."
		for self.lineIndex in xrange( len( self.lines ) ):
			line = self.lines[ self.lineIndex ]
			splitLine = line.split()
			firstWord = gcodec.getFirstWord( splitLine )
			if firstWord == '(<decimalPlacesCarried>':
				self.decimalPlacesCarried = int( splitLine[ 1 ] )
			elif firstWord == '(<extrusionWidth>':
				self.extrusionWidth = float( splitLine[ 1 ] )
			elif firstWord == '(</extruderInitialization>)':
				self.addLine( '(<procedureDone> multiply </procedureDone>)' )
				self.addLine( line )
				self.lineIndex += 1
				return
			self.addLine( line )

	def parseLine( self, line ):
		"Parse a gcode line and add it to the multiply skein."
		splitLine = line.split()
		if len( splitLine ) < 1:
			return
		firstWord = splitLine[ 0 ]
		if firstWord == '(<layer>':
			self.addLayer()
			self.addLine( line )
			return
		elif firstWord == '(</extrusion>)':
			self.addLayer()
			self.shouldAccumulate = False
		if self.shouldAccumulate:
			self.layerLines.append( line )
			return
		self.addLine( line )

	def setCorners( self ):
		"Set maximum and minimum corners and z."
		locationComplexes = []
		for line in self.lines[ self.lineIndex : ]:
			splitLine = line.split()
			firstWord = gcodec.getFirstWord( splitLine )
			if firstWord == 'G1':
				location = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )
				locationComplexes.append( location.dropAxis( 2 ) )
				self.oldLocation = location
		cornerHighComplex = euclidean.getMaximumFromPoints( locationComplexes )
		cornerLowComplex = euclidean.getMinimumFromPoints( locationComplexes )
		self.extent = cornerHighComplex - cornerLowComplex
		self.shapeCenter = 0.5 * ( cornerHighComplex + cornerLowComplex )
		self.separation = self.multiplyPreferences.separationOverExtrusionWidth.value * self.extrusionWidth
		self.extentPlusSeparation = self.extent + complex( self.separation, self.separation )
		columnsMinusOne = self.numberOfColumns - 1
		rowsMinusOne = self.numberOfRows - 1
		self.arrayExtent = complex( self.extentPlusSeparation.real * columnsMinusOne, self.extentPlusSeparation.imag * rowsMinusOne )
		self.arrayCenter = 0.5 * self.arrayExtent


def main():
	"Display the multiply dialog."
	if len( sys.argv ) > 1:
		writeOutput( ' '.join( sys.argv[ 1 : ] ) )
	else:
		preferences.displayDialog( MultiplyPreferences() )

if __name__ == "__main__":
	main()
