# originally written by sam hodge at  http://www.hodge.net.au/sam/blog/?p=250
import os
import maya
DEBUG=0

def log(message,prefix="Debug",hush=False):
    if not hush:
        print("%s : %s " % (prefix,message))
 

def getShapeData(shapeNode):
    ''' '''
    vertexValues = []
    vertNormalValues =[]
    textureValues =[]
    vertList = []
    vertNormalList = []
    vertTextureList = []
    faceNormals=[]
    faceValues = []

    #Verts
    numVerts = maya.cmds.polyEvaluate(shapeNode, vertex=True)
    if DEBUG:
        log("NumVerts : %s" % numVerts)
        print "shapeNode:", shapeNode
    vertexValues = [maya.cmds.pointPosition("%s.vtx[%d]" % (shapeNode, p)) for p in range(numVerts)]
    if DEBUG:
        log("Verticies:" +  str(vertexValues))
 
    #Normals
    numFaceNormals = 0
    for face in range(maya.cmds.polyEvaluate(shapeNode, face=True)):
        comp="%s.f[%d]" % (shapeNode,face)
        vertexFaces = maya.cmds.polyListComponentConversion(comp, fromFace=True,toVertexFace=True)
        vertexFaces= maya.cmds.filterExpand(comp, vertexFaces,selectionMask=70,expand=True)
        faceNormals.append([])
        for vertexFace in vertexFaces:
            vertNormalValues.append(maya.cmds.polyNormalPerVertex(vertexFace, query=True, xyz=True))
            numFaceNormals  += 1
            faceNormals[-1].append(numFaceNormals )
    if DEBUG:
        log("Num Face Normals: " + str(numFaceNormals))
        log("Face Normals: " + str(vertNormalValues))
 
    #Texture Coordinates
    numTexVerts = maya.cmds.polyEvaluate(shapeNode, uvcoord=True)
    log("NumTexVerts: " + str(numTexVerts))
    textureValues = [maya.cmds.getAttr("%s.uvpt[%d]" % (shapeNode,i)) for i in range(numTexVerts)]
    if DEBUG:
        log("Texture Coordinates: " + str(textureValues))
 
    ################## Faces
    numFaces = maya.cmds.polyEvaluate(shapeNode, face=True)
    if DEBUG:
        log("NumFaces : %s\n" % numFaces)

    vnIter = 0
    for faceNum in range(numFaces):
        log("\nFace %d of %d" % (faceNum+1, numFaces))
        oFace="%s.f[%d]" % (shapeNode, faceNum )

        ############## Verts (v)
        faceVerts = maya.cmds.polyInfo(oFace, faceToVertex=True)
 
        #This is hacky and should be replaced with snazzy regex
        faceVerts =  [int(fv)+1 for fv in faceVerts[0].split(":")\
	    [-1].strip().replace("  "," ").replace("  "," ").replace("  "," ").replace(" ",",").split(",")] 
        log("v: " + str(faceVerts) )
        vertList.append(faceVerts)
 
        ################## Normals (vn)
        if DEBUG:
            log("vn: " + str(faceNormals[faceNum]))
        vertNormalList.append(faceNormals[faceNum])

        ################# Texture (vt)
        tex =maya.cmds.polyListComponentConversion(oFace, fromFace=True,toUV=True)
        tex= maya.cmds.filterExpand(tex,selectionMask=35,expand=True)
      
        tex=[int(i.split("map")[-1].strip("[]")) +1 for i in tex]
        if DEBUG:
            log("vt: " + str(tex))

        # uv need to get in same order as vertex ordering
        tmpDict = {}
        for t in tex:
            component="\n%s.map[%d]" % (shapeNode,t-1)
            vertFromTex = maya.cmds.polyListComponentConversion(component, fromUV=True, toVertex=True)
            if DEBUG:
                print t,  "vertFromTex", vertFromTex, "component:", component
            if vertFromTex:
                index=int(vertFromTex[0].split("[")[-1].split("]")[0]) + 1
                tmpDict[index] = t

        orderedTex=[]
        for vert in vertList[-1]:       
            orderedTex.append(tmpDict[vert])
            vertTextureList.append(orderedTex)
    
        ###############
        face = " ".join( ["%d/%d/%d" % (vertList[-1][j], vertTextureList[-1][j], \
            vertNormalList[-1][j]) for j in range( len( vertTextureList[-1] ) ) ] )
        faceValues.append(face)    
        if DEBUG:        
            log("")
            log("f: " +  face)
            log("--")

    return {"v":vertexValues,"vn":vertNormalValues,"vt":textureValues,"f":faceValues,"g":shapeNode}


def writeData(dataDict):
    ''' '''
    outString = "\ng default\n"
    print "dataDict:", dataDict
   
    for i in dataDict["v"]: 
        if DEBUG:
            log(str(i))
        outString+= "v %f %f %f \n" % (i[0],i[1],i[2])
    for i in dataDict["vt"]:
        if DEBUG:
            log(str(i))
        outString+= "vt %f %f \n" % (i[0][0],i[0][1])
    for i in dataDict["vn"]:
        if DEBUG:
            log(str(i))
        outString+= "vn %f %f %f \n" % (i[0],i[1],i[2])
    outString += "g %s\n" % dataDict["g"]
    for i in dataDict["f"]:
        if DEBUG:
            log(str(i))
        outString += "f %s\n" % i

    outString += "\n"
    log(outString)

    return outString
 
def export(fileLocation, objList=[]):        
    ''' '''
    if objList==[]:
        objList=maya.cmds.ls(sl=1, l=1)
   
    filePaths=[]
    if objList and len(objList)>0:
        for obj in objList:
            data = getShapeData(obj)
            string = writeData(data)
            fName="%s.obj"% obj.replace("|","_" )
            fPath=os.path.join(fileLocation, fName)
            f = open(fPath,"w")
            if f:
		print "writing to", fPath
                f.writelines(string)
                f.close() 
		filePaths.append(fPath)
    else:
        print "Nothing to export"
    return filePaths

def main():
    fileLocation = "/home/FUELVFX/katrin"
    export(fileLocation,objList=[] )


main()
