# <body[^>]*>\s*(?:<h[^>]*>[^<]*</h\d>)?\s*<dl[^>]*>\s*<dt[^>]*>\[<a\b(?:(?!</dl).)+</dl>\s*</body>

from calibre.gui2.tweak_book import current_container
from calibre.gui2.tweak_book.boss import get_boss
from calibre.ebooks.oeb.polish.split import merge

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    
    if match is None:	# this is the last passage (all matches found)
        container = current_container()
        # Merge files whose name is in the list 'note_files_list'
        # (stored in persistent dict 'data', a parameter of replace()) 
        # into the file_whose name s in 'merge_master' (also stored in data)
        merge(container, 'text', data['note_files_list'], data['merge_master'])
        get_boss().apply_container_update_to_gui() 
        
        ######## hack temporary, to be deleted
        container.commit('test2.epub'1, True)
        
    else:

        if 'note_files_list' not in data :  
            # data is empty, therefore it's the 1st passage 
            # The master of the merge is the 1st note file
            data['note_files_list'] = [file_name]
            data['merge_master'] = file_name
            
            # Ask for a passage after the last find (match will be None)
            # Ask for processing the files in the order they appear in the book
            replace.call_after_last_match = True
            replace.file_order = 'spine'

        else:
            # Increments the list of files by adding the name of the file containing the note
            data['note_files_list'].append(file_name)
     
        return match.group()

