

KNOBNAME_KEEP = "keep"
KNOBNAME_DELETE = "delete"

nodeTemplate = """
Group {
 name MetaDataCleaner
 addUserKnob {20 properties l Properties}
 addUserKnob {1 delete l "Delete" t}
 addUserKnob {1 keep l "Keep" t}
 addUserKnob  {26 ""}

 knobChanged "metaDataCleaner.userKnobChanged()"

}
 Input {
  inputs 0
  name Input1
  xpos 0
 }
 ModifyMetaData {
  metadata {
  }
  name ModifyMetaData
  xpos 0
  ypos 150
 }
 Output {
  name Output1
  xpos 0
  ypos 300
 }

end_group
"""

metaDataLineTemplate = """{remove "%s" ""}"""


def createNode():
    from PySide2 import QtWidgets
    QtWidgets.QApplication.clipboard().setText(nodeTemplate)
    newNode = nuke.nodePaste("%clipboard%")
    nuke.addKnobChanged(userKnobChanged, node=newNode)
    pass



def userKnobChanged():
    if ((nuke.thisKnob().name() == KNOBNAME_DELETE) or
        (nuke.thisKnob().name() == KNOBNAME_KEEP)):

        updateModifyMetadata()

def updateModifyMetadata():
        # set values for each frame
    import shlex
    import fnmatch

    keeplist = shlex.split(nuke.thisNode().knob(KNOBNAME_KEEP).value())
    removelist = shlex.split(nuke.thisNode().knob(KNOBNAME_DELETE).value())  # get the metadata node


    metaKeys = list()

    for key in nuke.thisNode().input(0).metadata().keys():

        doKeep = False;
        # check for remove
        for keep in keeplist:
            if (checkPattern(keep, key)):

                # do nothing, keep this string
                doKeep =True;
                break;


        if (doKeep):
            continue;
        # check for remove
        for remove in removelist:
            if (checkPattern(remove, key)):
                # add to remove list
                metaKeys.append(metaDataLineTemplate % (key))

    # do the stuf
    mmd = nuke.allNodes(group=nuke.thisGroup(), filter="ModifyMetaData")[0]
    mmd["metadata"].fromScript("\n".join(metaKeys));

def checkPattern(fnpattern, string):
    import fnmatch, re
    regex = fnmatch.translate(fnpattern)
    reobj = re.compile(regex)

    if (reobj.match(string) is not None):
        #nuke.debug(" checking: %s = %s: TRUE" % (fnpattern, string))
        return True
    #nuke.debug(" checking: %s = %s: FALSE" % (fnpattern, string))
    return False
