## written by stefan ihringer (stefan@bildfehler.de)
##
## version 1.0: inserts tx_nukeLensDistortion and fills in values from file automatically
## todo: get width&height from selected node instead of root format

import nuke


def _get_size():
    try:
        width, height = nuke.selectedNode().width(), nuke.selectedNode().height()
    except:
        width, height = nuke.knob("format").split(" ")[:2]
    return int(width), int(height)


def insert_tx_lensdistortion():
    """
    """

    width, height = _get_size()

    panel = nuke.Panel("Paste 2nd line from lens txt file")
    panel.addSingleLineInput("lens data:", "")
    panel.addSingleLineInput("frame width:", width)
    panel.addSingleLineInput("frame height:", height)
    panel.addButton("Cancel")
    panel.addButton("OK")

    if panel.show() == 0:
        nuke.createNode("tx_nukeLensDistortion")
        return

    try:
        width = int(panel.value("frame width:"))
        height = int(panel.value("frame height:"))
    except:
        width, height = _get_size()

    try:
        rawdata = [float(i) for i in panel.value("lens data:").split(" ")]
    except:
        nuke.createNode("tx_nukeLensDistortion", "width_knob %d height_knob %d oFOVX_knob %d oFOVY_knob %d" % (width, height, width, height))
        return

    # remove camera data and pixel aspect from string array
    lens = rawdata[4:6] + rawdata[7:12]

    # convert float offsets to pixels
    lens[0] = round(float(width) * lens[0])
    lens[1] = round(float(height) * lens[1])
    # add frame size parameters
    lens = [width, height, width, height] + lens

    params = "width_knob %d height_knob %d oFOVX_knob %d oFOVY_knob %d lensCentreOffsetX_knob %d lensCentreOffsetY_knob %d lensDistortion_knob %s anamorphicSqueeze_knob %s curvatureX_knob %s curvatureY_knob %s quarticDistortion_knob %s" % tuple(lens)
    thenode = nuke.createNode("tx_nukeLensDistortion", params)

