import re, os, math
import nuke, nukescripts



class CreateFolders(KellerNukePlugin):

    def configurePlugin(self):
        menubar = nuke.menu("Nuke")
        m = menubar.addMenu("&Render")
        m.addCommand("CreateFolders",'createFolders.createFolders()', "F16")
        pass
    


##########################
def createFolders():
    writeNodes = get_broken_write_nodes()
    if writeNodes:
       fix_broken_write_nodes()


def get_broken_write_nodes():
    """
    Returns list of all write nodes that refer to non-existing paths (or an empty list).
    If nodes are selected only they will be checked.
    """

    nodes = nuke.selectedNodes() 
    if not nodes: nodes = nuke.allNodes() 
    n = [i for i in nodes if i.Class() == "Write"]
    result = []
    for curNode in n:
        fileKnob = curNode['file']
        try:
            if not os.path.exists(os.path.dirname(fileKnob.evaluate())):
                result.append(curNode)
        except:
            pass

    return result



def fix_broken_write_nodes():
    """
    Create paths for all (selected) write nodes in case they don't exist yet.
    """

    nodes = get_broken_write_nodes()
    for curNode in nodes:
        thePath = os.path.dirname(curNode['file'].evaluate())
        if thePath and not os.path.exists(thePath):
            try:
                os.makedirs(thePath)
                print ("created directory "+thePath)
            except:
                nuke.message("CreateFolders.fix_broken_write_nodes(): Error creating "+thePath)