import time, threading
import nuke, nukescripts, nuke.geo
from nukescripts import snap3d as s3d

def processIt(frange,axisType,minVertices):

    #ax = nuke.createNode('Axis2', inpanel=False)
    #nuke.autoplace(ax)
    
    #ax = nuke.selectedNode()
    ax = nuke.thisNode()      
      
    print "Creating Axis node " + ax.name()
    print "Keying for " + axisType
    if (axisType == 'position'):
        if ax['translate'].isAnimated():
            ax['translate'].clearAnimated()
        ax['translate'].setAnimated()
    elif (axisType == 'position-orientation'):
        if ax['translate'].isAnimated():
            ax['translate'].clearAnimated()
        ax['translate'].setAnimated()
        if ax['rotate'].isAnimated():
            ax['rotate'].clearAnimated()
        ax['rotate'].setAnimated()
    elif (axisType == 'position-orienation-size'):
        if ax['translate'].isAnimated():
            ax['translate'].clearAnimated()
        ax['translate'].setAnimated()
        if ax['rotate'].isAnimated():
            ax['rotate'].clearAnimated()
        ax['rotate'].setAnimated()
        if ax['scaling'].isAnimated():
            ax['scaling'].clearAnimated()
        ax['scaling'].setAnimated()
    
    task = nuke.ProgressTask("Setting Axis " + str(frange))
    print "Frames " + str(frange)
    totalfrange = frange.frames()
    percentage=0
    
    curFrame = nuke.frame()
    print "Viewer is currently set at frame " + str(curFrame)
    
    print "Setting viewer to start frame " + str(frange.first())
    nuke.activeViewer().frameControl(-6) 
                  
    for f in frange:
        percentage = ((f - frange.first()) * 100) / totalfrange
        #print "Percentage ... " + str(percentage)
        print "Frame " + str(f)
        task.setMessage("Processing ... " + str(f))
        if task.isCancelled():
            nuke.executeInMainThread( nuke.message, args=( "Oh well!" ) )
            break;
        else:            
            nuke.executeInMainThread(setKeys, args=(ax,axisType,minVertices,percentage,))
            for a in nuke.allNodes():
                if a.Class()=="ReadGeo":
                    print "Reloading geo " + str(a.name())
                    a.knob('reload').execute()
            task.setProgress(percentage)
            time.sleep(.2)
            
    print "Moving viewer back to " + str(curFrame)
    nuke.frame(curFrame)
    
def setKeys(node,axisType,minVertices,percentage):

    try:
        s3d.verifyVertexSelection(s3d.getSelection(), minVertices) 
        if (axisType == 'position'):
            s3d.translateToPoints(node)
        elif (axisType == 'position-orientation'):
            s3d.translateRotateToPoints(node)
        elif (axisType == 'position-orienation-size'):
            s3d.translateRotateScaleToPoints(node)
                
        nuke.activeViewer().frameControl(1)
    
    except ValueError, e:
        nuke.message(str(e))

def popUp():

    curViewer = nuke.activeViewer()
    viewerNode = curViewer.node()
    framerange = ''
    framerangeViewer = ''
    framerangeViewer = viewerNode['frame_range'].getValue()
    if framerangeViewer != '' and viewerNode['frame_range_lock'].getValue() == 1.0:
        framerange = framerangeViewer
    else:
        framerange = str(nuke.root().firstFrame()) + '-' + str(nuke.root().lastFrame())
    print framerange
        
    optionsList = 'position position-orientation position-orienation-size'
    p = nuke.Panel("Snap Axis")
    p.addSingleLineInput("Frames:", framerange)
    p.addEnumerationPulldown("Type:", optionsList)  
    p.addButton("Cancel")
    p.addButton("Create")

    result = p.show()
    axisType = p.value("Type:")
    frames = p.value("Frames:")
  
    frange = nuke.FrameRange(frames)
    
    if axisType:
  
        if (axisType == 'position-orienation-size'):
            minVertices=3
        else:
            minVertices=1
            
        try:    
            s3d.verifyVertexSelection(s3d.getSelection(), minVertices)       
            threading.Thread(target=processIt, args=(frange,axisType,minVertices, )).start()
    
        except ValueError, e:
            nuke.message(str(e))
    
    