import re
class SearchReplacePanel( nukescripts.PythonPanel ):
    def __init__( self ):
        nukescripts.PythonPanel.__init__( self, 'Search and Replace', 'com.ohufx.SearchReplace')

        # CREATE KNOBS
        self.nodesChoice = nuke.Enumeration_Knob( 'nodes', 'Source Nodes', ['all', 'selected'])
        self.searchStr = nuke.String_Knob('searchStr', 'Search for:')
        self.update = nuke.PyScript_Knob('update', 'Update')
        self.info = nuke.Multiline_Eval_String_Knob('info', 'Found')
        self.info.setEnabled( False )
        self.replaceStr = nuke.String_Knob('replaceStr', 'Replace with:')
        self.replace = nuke.PyScript_Knob('replace', 'Replace')
        # ADD KNOBS
        self.addKnob( self.nodesChoice )
        self.addKnob( self.searchStr )
        self.addKnob( self.update )
        self.addKnob( self.info )
        self.addKnob( self.replaceStr )
        self.addKnob( self.replace )

    def search( self, nodes ):
        nodeMatches, knobMatches = OhuMisc.search( self.searchStr.value(), nodes )
        nodes = [n.name() for n in nodeMatches]
        infoStr = '%s node(s) found:\n\t%s' % ( len(nodes), ', '.join( nodes ) )
        self.info.setValue( infoStr )
        return knobMatches

    def knobChanged( self, knob ):
        srcNodes = { 'all': nuke.allNodes(), 'selected': nuke.selectedNodes() }
        if knob in (self.searchStr, self.update, self.nodesChoice):
            self.search( srcNodes[self.nodesChoice.value()] )
        elif knob == self.replace:
            for k in self.search( srcNodes[self.nodesChoice.value()] ):
                newStr = re.sub( self.searchStr.value(), self.replaceStr.value(), k.value() )
                k.setValue( newStr )

            

def addPanel():
    return SearchReplacePanel().addToPane()

menu = nuke.menu('Pane')
menu.addCommand('SearchReplace', addPanel)


nukescripts.registerPanel('com.ohufx.SearchReplace', addPanel)
