from markdown import Extension
import xml.etree.ElementTree as etree
import copy
import html

from markdown import Extension
from markdown.preprocessors import Preprocessor
from markdown import util as md_util
import xml.etree.ElementTree as etree
import re

DEFAULT_CONFIG = {}

RE_STATIC=r"""\\*\{% *static '(?P<group1>[/a-zA-Z0-9-_=.+]*)' *%\\*\}"""

class FindReplaceProcessor(Preprocessor):

    def __init__(self,find,replace,*args,**kwargs):
        self.find = find
        self.replace = replace
        super().__init__(*args,**kwargs)

    def replace_static(self,text):
        results = re.sub(self.find,self.replace,text)
        return results

    def run(self,lines):
        new_lines = []
        for line in lines:
            m = re.search(RE_STATIC, line)
            if not not m:
                newline = self.replace_static(line)
                print(line,newline)
                line= newline
            new_lines.append(line)
        return new_lines

class FindReplaceExtension(Extension):
    def __init__(self, *args, **kwargs):

        self.config = {
            'find': [RE_STATIC,'REGEX search string'],
            'replace': [r'\g<group1>','the replacement string']
        }

        super().__init__(*args, **kwargs)

    def extendMarkdown(self, md):
        """Add support for keys."""

        find=self.getConfig('find')
        replace=self.getConfig('replace')

        md.preprocessors.register(StaticProcessor(find,replace),'static_processor',200)
        
def makeExtension(*args, **kwargs):
    return FindReplaceExtension(*args, **kwargs)