## read_from_write.py
##
## written by stefan ihringer (stefan@bildfehler.de)
## parts by Diogo Girondi (diogogirondi@gmail.com) http://www.creativecrash.com/nuke/downloads/scripts-plugins/c/read-from-write
##
## version 1.0 (2010-06-07)
## version 1.1 Martin Saechsinger: fixed colorspace when using OCIO.

import nuke
import os, re


def _get_directory(rawpath):
    """
    Make a path cross-platform by replacing network shares 
    """
    path = rawpath
    if (nuke.env["WIN32"]):
        path = path.replace("/Volumes/O/", "//calculon/o/")
        path = path.replace("/","\\")
    else:
        path = path.replace("//calculon/o/", "/Volumes/O/")

    return os.path.dirname(path)


def _hashreplace(match):
    """
    Internally called by regular expression.
    Replaces #### by %04d (or any other number of hashes)
    """
    return "%%0%dd" % len(match.group())


def ReadFromWrite():
    """
    Creates a read node from a selected write node.
    """

    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

    # get values from Write knobs
    filestr = the_node.knob("file").value()
    proxystr = the_node.knob('proxy').value()
    colorstr = int(the_node.knob('colorspace').getValue())
    #colorstr = the_node.knob('colorspace').value()
    premult = the_node.knob('premultiplied').value()
    rawdata = the_node.knob('raw').value()
    xpos = the_node.knob('xpos').value()
    ypos = the_node.knob('ypos').value()

    # #-Zeichen finden (falls vorhanden) und durch ein Konstrukt wie %04d ersetzen.
    filestr = re.sub("#+", _hashreplace, filestr)

    # Dateiliste holen um automatisch ersten und letzten Frame zu erkennen
    # (von http://www.vfxtalk.com/forum/showpost.php?p=79846&postcount=15)
    expaddpatt = re.compile(r"(?<=\.)\d*(?=\.)")
    paddpatt   = re.compile(r'%+\d+d')
    try:
        padding = paddpatt.search(filestr).group()
        seqlist = sorted(glob.glob(paddpatt.sub("*",filestr)))
        start = int(padding % (int(expaddpatt.search(seqlist[0]).group())))
        end = int(padding % (int(expaddpatt.search(seqlist[-1]).group())))
    except:
        # wenn Sequenzlaenge nicht ermittelbar (z.B. kein Dateiname in der write-node)
        # wird als default die Shotlaenge verwendet:
        start = int(nuke.root().knob('first_frame').value())
        end = int(nuke.root().knob('last_frame').value())

    new_read = nuke.nodes.Read(file = filestr, proxy = proxystr, first = start, last = end, colorspace = colorstr, premultiplied = premult, raw = rawdata)
    new_read.knob('xpos').setValue(xpos + 80)
    new_read.knob('ypos').setValue(ypos + 80)
    nuke.inputs(new_read, 0)

