# -*- coding: utf8 -*-

'''
Generic BioCASE tools for working with HTML.

$RCSfile: htmltools.py,v $
$Revision: 927 $
$Author: markus $
$Date: 2008-05-11 00:50:29 +0200 (So, 11. Mai 2008) $
'''

########################################
import re
from types import *
########################################



# ------------------------------------------------------------------------------------
class ankerClass:
    '''Class which takes a string and creates an HTML anker for existing links.'''
    linkPat  = re.compile('''(?P<link>(?:ftp|http|mailto):.*?)(?:[\s"']|$)''', re.IGNORECASE | re.DOTALL)
    ankerPat = re.compile('''<a[^>]+?>''', re.IGNORECASE | re.DOTALL)
    
    def createLinks(self, data):
        '''Create a html link if data contains a URI'''
        if type(data) in (StringType, UnicodeType):
            ankers = self.__class__.ankerPat.findall(data)
            placeholder = u'_!"�$%&_'*5
            ankerLessData = self.__class__.ankerPat.sub(placeholder, data)
            data = self.__class__.linkPat.sub(r'<a href="\g<link>">\g<link></a>', ankerLessData)
            for anker in ankers:
                data = data.replace(placeholder, anker, 1)
        return data
    


def getDropDownOptionHtml(vals=None, default=None, keysSorted=[]):
    options = ''
    if type(vals) == DictType:
        if len(keysSorted)<1:
            # sorted keys not yet provided. Sort alphabetically
            keysSorted = vals.keys()
            keysSorted.sort()
        for k in keysSorted:
            v = vals[k]
            sel = ''
            if default==v:
                sel = ' selected'
            if k is not None:
                options += '''<option value="%s"%s>%s</option>\n''' %(v,sel,k)
    else:
        for v in vals:
            sel = ''
            if default==v:
                sel = ' selected'
            if v is not None:
                options += '''<option%s>%s</option>\n''' %(sel, v)
    return options

def getDropDownHtml(name, vals=None, default=None):
    return '''<select name="%s">%s</select>'''%(name, getDropDownOptionHtml(vals, default))

def escapeHtml(text):
    "Escape a few HTML special chars with HTML entities."
    for s, h in [('&', '&amp;'), #order is important
        ('<', '&lt;'),
        ('>', '&gt;'),
        ('"', '&quot;')]:
        text = text.replace(s,h)
    return text

def escapeBackslash(text):
    "Escape the backslash / into //."
    return text.replace(chr(92), chr(92)+chr(92))




    
# ------------------------------------------------------------------------------------
if __name__ == '__main__':
    ank = ankerClass()
    data = '''http://www.parks.org.il'''
    print data
    print "-"*40
    print ank.createLinks(data)
