#!/usr/bin/env python 

'''
Copyright (C) 2007 hugomatic... 
based on dots.py (C) 2005 Aaron Spike, aaron@ekips.org

This program 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.

This program 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 this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''
import inkex, simplestyle, simplepath
import os

class Gcode(inkex.Effect):
    def __init__(self):
        inkex.Effect.__init__(self)
        self.OptionParser.add_option("-d", "--directory",
                        action="store", type="string", 
                        dest="directory", default="/home/",
                        help="Directory for gcode file")

        self.OptionParser.add_option("-f", "--file",
                        action="store", type="string", 
                        dest="file", default="-1.0",
                        help="File name")			

        self.OptionParser.add_option("-u", "--scaleX",
                        action="store", type="float", 
                        dest="scaleX", default="10.0",
                        help="Scale factor X")	

        self.OptionParser.add_option("-v", "--scaleY",
                        action="store", type="float", 
                        dest="scaleY", default="-10.0",
                        help="Scale factor Y")	

        self.OptionParser.add_option("-x", "--offsetX",
                        action="store", type="float", 
                        dest="offsetX", default="0.0",
                        help="Offset along X")	

        self.OptionParser.add_option("-y", "--offsetY",
                        action="store", type="float", 
                        dest="offsetY", default="11.0",
                        help="Offset along Y")

        self.OptionParser.add_option("-s", "--safeZ",
                        action="store", type="float", 
                        dest="safeZ", default="0.5",
                        help="Z above all obstacles")

        self.OptionParser.add_option("-z", "--surfaceZ",
                        action="store", type="float", 
                        dest="surfaceZ", default="0.0",
                        help="Z above all obstacles")

        self.OptionParser.add_option("-c", "--cutZ",
                        action="store", type="float", 
                        dest="cutZ", default="-0.125",
                        help="Z depth of cut")

        self.OptionParser.add_option("-p", "--feed",
                        action="store", type="float", 
                        dest="feed", default="4.0",
                        help="Feed rate in in/min")

    def effect(self):
        xScale = self.options.scaleX  * 0.001 # 8.5 / 744.1
        yScale = self.options.scaleY * 0.001 #-11.0 / 1052.37
        xOffset = self.options.offsetX
        yOffset = self.options.offsetY
        safeZ = self.options.safeZ
        surfaceZ = self.options.surfaceZ
        cutZ = self.options.cutZ
        feed = self.options.feed
        

        fileName = os.path.join(self.options.directory, self.options.file)
        ngcfile = open(fileName, 'wb')
        ngcfile.write("G20\nF%.4f\n" % feed)
        ngcfile.write("G0 Z%.4f\n (move out of the way)" % safeZ)
        
        for id, node in self.selected.iteritems():
            ngcfile.write("\n(ID " + str(id) + ")\n")
            
            if node.tagName == 'path':
                self.group = self.document.createElement('svg:g')
                node.parentNode.appendChild(self.group)
                new = self.document.createElement('svg:path')
                
                try:
                    t = node.attributes.getNamedItem('transform').value
                    self.group.setAttribute('transform', t)
                except AttributeError:
                    pass

                p = simplepath.parsePath(node.attributes.getNamedItem('d').value)

                for cmd,params in p:
                    if cmd == 'M':
                        xPath = float(params[-2])
                        yPath = float(params[-1])
                                                
                        x = xPath * xScale + xOffset
                        y = yPath * yScale + yOffset
                        ngcfile.write("g00 Z%.4f\n (approaching)" % surfaceZ)
                        ngcfile.write("g00 X%.4f Y%.4f\n (fly above next cut)" % (x,y))
                        
                        ngcfile.write("g01 Z%.4f\n (plunging)" % cutZ)
                        ngcfile.write("g01 X%.4f Y%.4f\n" % (x,y))
                        continue
                                        
                    if cmd == 'C':
                        xa = float(params[0])
                        ya = float(params[1])
                        xb = float(params[2])
                        yb = float(params[3])
                        xc = float(params[4])
                        yc = float(params[5])
                        self.interpolate(ngcfile, xa,ya, xb,yb, xc,yc, 10)

                        
                    if cmd != 'Z':
                        xPath = float(params[-2])
                        yPath = float(params[-1])
                        x = xPath * xScale + xOffset
                        y = yPath * yScale + yOffset
                        ngcfile.write("g01 X%.4f Y%.4f\n" % (x,y))
                    
                ngcfile.write("G0 Z%.4f\n (move out of the way)" % safeZ)
        ngcfile.write("G00 Z%.4f\n" % safeZ)
        ngcfile.write("M2\n")
        ngcfile.close()
                

    def interpolate(self, ngcfile, xa,ya, xb,yb, xc,yc, nbOfPoints):
        
        ngcfile.write("(C [%.4f, %.4f] [%.4f, %.4f] [%.4f, %.4f])\n" %(xa,ya, xb, yb, xc,yc))
        
    
e = Gcode()
e.affect()
