from PIL import Image
import os
from urllib.parse import unquote

def fixup(doc,location):
    for e in tuple(doc.findAll('reveal')):
        div = doc.new_tag('div')
        e.replace_with(div)
        div.attrs['title'] = 'Image revealer'
        div.attrs['class'] = 'reveal'
        
        src = e['src']
        href = e['href']
        title = e['title']
        
        div.attrs['data-src'] = src
        div.attrs['data-href'] = href
        div.attrs['data-title'] = title        
        if 'scale' in e.attrs:
            scale = float(e['scale'])
        else:
            scale = None
            
        with Image.open(os.path.join(location,unquote(src))) as image:
            width = image.width
            if scale:
                width = int(width*scale)
            width = str(width)
            div.attrs['data-width'] = width
            div.attrs['style'] = 'hoowidth: '+width+'px'
            height = image.height
            if scale:
                height = int(height*scale)
            div.attrs['data-height'] = str(height)            
        
        i = doc.new_tag('i')
        i.append(title)
        a = doc.new_tag('a')
        a.attrs['href'] = src
        a.append(i)
        div.append(a)
        div.append(" [see ")
        a = doc.new_tag('a')
        a.attrs['href'] = 'script.js'
        a.append('the reveal script')
        div.append(a)
        div.append(' to see if you want to run it, or just go ')
        a = doc.new_tag('a')
        a.attrs['href'] = src
        #a.attrs['target'] = '_blank'
        a.append('here')
        div.append(a)
        div.append(' to see the picture, or ')
        a = doc.new_tag('a')
        a.attrs['href'] = href
        #a.attrs['target'] = '_blank'
        a.append('here')
        div.append(a)
        div.append(" for the picture's source.]")
