## set_prerenderdirectory.py
##
## version 1.0 (2010-07-08): initial version based on set_renderdirectory
##


import re, os, math
import nuke, nukescripts

default_format   = "exr"
scripts_folder   = "Comp"
render_folder    = "450_PreComp"

debug_flag       = True

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


def setPrerenderdirectory():
    """
    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]

    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")

    # ask for pretender description
    label = "pre"
    panel = nuke.Panel("Set pre-render directory")
    panel.addSingleLineInput("Label:", label)
    panel.addButton("Cancel")
    panel.addButton("OK")
    if panel.show() == 0:
        return

    # clean label for use in filenames
    label = panel.value("Label:")
    label = re.sub("[^\w-]","",label)

    new_path = new_path + "/" + script_name + "_" + label
    the_node.knob("file").setValue(new_path + "/" + script_name + "_" + label + ".####." + default_format)
    print "set pre-render 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
