from markdown import Extension
from markdown.treeprocessors import Treeprocessor
import xml.etree.ElementTree as etree
import html
import copy
import re

class GlightboxProcessor(Treeprocessor):

    def run(self,root):

        parent_of = {child:parent for parent in root.iter() for child in parent}

        for image in root.iter('img'):
            parent=parent_of[image]
            try:
                classes = image.get('class').lower().split(' ')
            except AttributeError:
                classes = []

            if 'skip-lightbox' in classes:
                continue

            parent = parent_of[image]

            if parent.tag=='a':
                continue

            for ii in range(len(parent)):
                if parent[ii]==image:
                    break
            del parent[ii]
            attrib_dict = {
                'class':'glightbox',
                'href':image.get('src')
                }

            description = image.get('alt')

            if description is not None:
                attrib_dict['data-glightbox']='description: '+ description
                

            newtag = etree.Element('a',attrib=attrib_dict)
            newtag.insert(0,image)
            parent.insert(ii,newtag)
        return root


class GlightboxExtension(Extension):
    def extendMarkdown(self, md):
        """Add support for keys."""
        md.treeprocessors.register(GlightboxProcessor(md), 'glightbox_processor', 19.99)

        
def makeExtension(*args, **kwargs):
    return GlightboxExtension(*args, **kwargs)