#!/usr/bin/python

import xml.dom.minidom
import copy

if __name__ == "__main__":
    # target_file = "/Applications/Firefox.app/Contents/MacOS/res/builtin/platformHTMLBindings.xml"
    target_file = "platformHTMLBindings.xml.orig"
    # yes, the grouping is redundant, but it is documentation, sortof
    new_bindings = [(key, mod, cmd) for key, mod, cmd in 
                    [line.strip().split(" ",2) for line in open("bindings_list", "r").readlines()]]
    
    blob = xml.dom.minidom.parse(target_file)
    indent_to_add = None
    for binding in blob.getElementsByTagName("binding"):
        binding_class = binding.getAttribute("id")
        print binding_class
        handler, = binding.getElementsByTagName("handlers")
        first_handler = handler.getElementsByTagName("handler")[0]
        print "first_handler", first_handler.toxml()
        if not indent_to_add:
            indent_to_add = handler.firstChild.cloneNode(None) # we just know
            print "indent_to_add", indent_to_add
        
        handler.insertBefore(indent_to_add, first_handler)
        for key, mod, cmd in new_bindings:
            handler_string = '<handler event="keypress" key="%s" modifiers="%s" command="%s"/>' % (key, mod, cmd)
            handler_to_add = xml.dom.minidom.parseString(handler_string).getElementsByTagName("handler")[0]
            handler.insertBefore(handler_to_add, first_handler)
            handler.insertBefore(indent_to_add, first_handler)
            indent_to_add = indent_to_add.cloneNode(None)


    print >> open("platformHTMLBindings.xml","w"), blob.toxml()
    # cp ./platformHTMLBindings.xml /Applications/Firefox.app/Contents/MacOS/res/builtin/

    # <binding id="inputFields">
    # <binding id="textAreas">
    # <binding id="editor">