## set_renderdirectory.py

##
## version 1.2 (2012-12-28): update for new file structure
## version 1.1 (2010-06-07): removed unused functions
## version 1.0 (2010-05-11): initial version
##
## todo: ask for pretender, select different format than dpx?


import re, os, math
import nuke, nukescripts

default_format   = "dpx"
scripts_folder   = "Comp"
render_folder    = "500_Renders"

debug_flag       = False

##########################


def setRenderdirectory():
    """
    change output filename of write node to proper render location
    """

    try:
        the_node = nuke.selectedNode()
        if the_node.Class() != "Write":
            nuke.message("Please select a write node.")
            return
    except:
        nuke.message("Please select a write node.")
        return

    # comp saved?
    if not nuke.knob("root.name"):
        if nuke.ask("Script needs a file name first.\nSave and continue?"):
            try:
                nuke.scriptSave()
            except RuntimeError:
                # if save dialog was cancelled
                return
        else:
            return

    # test if script name is valid
    script_name = nuke.knob("root.name")
    script_path = os.path.dirname(script_name)
    script_name = os.path.splitext(os.path.basename(script_name))[0]
	
    nuke.message("DEBUG: script_name" +script_name)
		

    new_path, num = re.subn("(?i)/"+scripts_folder+"/","/"+render_folder+"/",script_path,1)
    if num == 0:
        nuke.message("Script is not saved in "+scripts_folder+".\nRender directory can't be determined.")
        return
    # todo: make sure there are no extra directories beyond sequence and scene number (no "050_scripts/010/010_010/blabla")

    new_path = new_path + "/" + script_name
    the_node.knob("file").setValue(new_path + "/" + script_name + ".####." + default_format)
    print "updated directory of "+the_node.name()
    print

    # create directory?
    if not debug_flag:
        if not os.path.exists(new_path):
            try:
                os.makedirs(new_path)
                print "created directory "+new_path
                print
            except:
                nuke.message("Error creating "+new_path)


# fin
