

#---parse svg use-----
import xml.etree.ElementTree as et
import math
import csv

startx = 10
starty = 10

def roundUp(coords, numDec):
    nl = []
    for ele in coords:
        x = round(ele[0], numDec)
        y = round(ele[1], numDec)
        nl.append((x,y))
    return nl


def cutRectangle(wd, ht):
    print "Cut Rectangle"
    print "Width = ", wd, "\tHeight = ", ht
    x = 0
    y = starty
    rect = []
    y = y + ht
    rect.append((x,y))
    x = x + wd
    rect.append((x,y))
    y = y - ht
    rect.append((x,y))
    x = x - wd
    rect.append((x,y))
    # return to entry point
    rect.append((0,0))
    rect = roundUp(rect,1)
    return rect


# numPoints is the resolution of cut
def cutCircle(r, numPoints):
    print "Cut Circle"
    print "Radius = ", r, "\tNum Pts = ", numPoints
    x = 0
    y = starty
    circle = []
    thinc = 360.0 / numPoints
    thetha = 180.0
    for i in range(0,numPoints+1):
        # print i, thetha
        angle = math.radians(thetha)
        rx = x + r * math.cos(angle) + r
        ry = y + r * math.sin(angle) + r
        circle.append((rx,ry))
        thetha = thetha + thinc
    circle.append((0,0))
    circle = roundUp(circle,1)
    return circle

def cutPath(pathlist):
    print "Cut Path"
    minX = 10000.0
    minY = 10000.0
    xpos = 0
    elePos = 0
    numEle = len(pathlist)
    for ele in pathlist:
        if ele[0] < minX:
            minX = ele[0]
            xpos = elePos
            # print "x =", minX
        if ele[1] < minY:
            minY = ele[1]
            ypos = elePos
            # print "y =", minY
        elePos = elePos + 1
    print "NumPts =", numEle, "\tMinX =", minX, "\tMinY = ", minY
    print "Start Point # =", xpos
    np = []
    for ele in pathlist:
        x = ele[0] - minX
        y = ele[1] - minY + starty
        np.append((x,y))
    # locate for the smallest x value
    # create newlist
    path = []
    ele = xpos
    for count in range(0,numEle):
        path.append(np[ele])
        ele = (ele + 1) % numEle
    path.append(path[0])
    path.append((0,0))
    path = roundUp(path,1)
    return path


#----end helper func-------------

def menu():
	menu = "please enter command to jog or load"
	print (menu)
	cmdIn = raw_input()
	print(cmdIn)
	#check for right format jog x 123
	cmdTok = cmdIn.split( )
	print(cmdTok)
	cmd1 = cmdTok[0] #chk for jog or load
	myPos = cmdTok[1] #chk for x or y or z
	dist = cmdTok[2] #chk for abs pos still within boundary after move
	#print(cmd1)
	#print(myPos)
	#print(dist)
	if cmd1 not in ("jog", "load"):
		print("wrong command")
		exit()
	if myPos not in ("x", "y", "z"):
		print("wrong pos")
		exit()
	if int(dist) > 100: #need to track max abs pos
		print("exceeded dist")
		exit()

	if cmd1 in "jog":
		myJog(myPos,int(dist))
	if cmd1 in "load":
		parseSVG(myPos,int(dist))
#end =====menu==========
		
def myJog(pos, dist):
	
	if pos in "x":
		moves = [[dist,0]]
	if pos in "y":
		moves = [[0,dist]]

	#moves = [[10,10],[20,20],[10,10],[0,0]]
	# Move!
	
#end =====myJog==========
#parseSVG()  from r.dorville mtm_svg2csv.py
def parseSVG():
    print "parseSVG from file"
    fname = raw_input("Enter filename: ")
    if len(fname) == 0:
        fname = "test2D.svg"
    elif fname.split('.')[1] != 'svg':
        print "Error:  only SVG files are processed."
        exit()
    try:
        fh = open(fname)
    except:
        print "Error: File (", fname, ") cannot be opened."
        exit()
    fh.close()

    filename = fname.split('.')[0]

    # read in svg file
    tree = et.parse(fname)
    plot = []
    skip = False
	
	#parse XML struct in SVG
    for element in tree.iter():
        # print element.tag
        # print element.tag.split('}')[1]
        property = element.tag.split('}')[1]
        # look for the groups g
        if property == 'g' :
            id = element.get('id')
            # skip everything except those in layer 1
            if id == 'layer1':
                skip = False
            else:
                skip = True
                continue
        if skip:
            continue
        #print property
        # layer 1 stuff

        if property == 'rect':
            print "\n\nRectangle"
            wd = float(element.get('width'))
            ht = float(element.get('height'))
            print "\twidth =", wd
            print "\theight=", ht
            plot = cutRectangle(wd, ht)
            # print plot
            break


        if property == 'circle':
            print "\n\nCircle"
            cx = float(element.get('cx'))
            cy = float(element.get('cy'))
            r  = float(element.get('r'))
            print "\tCenter (x,y) = (", cx , ",", cy, ")"
            print "\tradius = ", r
            plot = cutCircle(r, 30)
            # print plot
            break

        #shin: ctrl+shift+p set path to absolute
		#set stroke to path
		#d containts abs path. see screenshot for details
        if property == 'path':
            print "\n\nPath"
            print "Stuff in d : \n", element.get('d')
            values = element.get('d')
            mylist = []
            for ele in values.split(' '):
                if ele in ("m", "M"):#if ele == 'm': #shin: weird, some capitalized M
                    continue
			
                if ele in ("c", "C"):#if ele == 'c': 
                    break
                print ele
                x = float(ele.split(',')[0])
                y = float(ele.split(',')[1])
                print "X=", x, "  Y=",y
                coord = (x, y)
                mylist.append(coord)
			
            print "----mylist----"
            print mylist
            x = 0.0
            y = 0.0
            newlist = []
            for element in mylist:
                x = element[0] + x
                y = element[1] + y
                coord = (x,y)
                newlist.append(coord)
            print '\t',newlist
            plot = cutPath(newlist)
            for ele in newlist:
              print ele

    # output the csv file
    csvfname = filename + '.csv'
    plotfile = open(csvfname, "w")
    out = csv.writer(plotfile, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
    for ele in plot:
        pt = (ele[0],ele[1],ele[0],ele[1])
        out.writerow(pt)
    plotfile.close()
    print "Output file: ", csvfname
    print "Done"		
#end parseSVG
	
#------IF RUN DIRECTLY FROM TERMINAL------
if __name__ == '__main__':
	
#def menu func
#cmd menu: jog and load svg.
#cmd: jog {x,y,z} 123
#pos: x or y or z
#123: abs mm movement; set limit on max. keep track of current abs move.
#load svg. parse xml to find the val d in the tree. then process the abs into array of [[x,y,z],[...]]
	#menu()
	parseSVG()

