# coding=UTF-8
# -*- coding: UTF-8 -*-
#various utilities for html rendering
# good stuff http://furius.ca/pubcode/
import codecs
import string, re
import os
import utilswin

# start some work (bound to configs
import configs as config
file_mask = config.file_mask
img_mask = config.img_mask
##generator_start_node_installs = config.generator_start_node_installs

re_img = re.compile(img_mask)

img_fnames = []
found_imgs = []
##proglist = []

img_fnames_rel2generator = {}
img_fnames_rel2generator['logos'] = os.listdir(os.path.abspath( config.img_root_rel2generator+'logos/'))
img_fnames_rel2generator['ss'] = os.listdir(os.path.abspath( config.img_root_rel2generator+'ss/'))


import mylibs
getftext = mylibs.getftext
putftext = mylibs.putftext
putftextU = mylibs.putftextU
fileExists = mylibs.fileExists


def look_for_img(name, img_subdir = 'logos'):
    imgtype = ''
    if img_exists(name+".png",  img_subdir = img_subdir) != '' :  imgtype = '.png'
    elif img_exists(name+".gif",  img_subdir = img_subdir) != '' : imgtype = '.gif'
    elif img_exists(name+".jpg", img_subdir = img_subdir)  != '' : imgtype = '.jpg'
    if imgtype: 
       return  config.img_root + img_subdir + '/' + name  +imgtype
    else: return ''    

def img_exists(fname,  img_subdir = 'logos'):
    for img in img_fnames_rel2generator[img_subdir]:
        if img.lower() == fname.lower():
            found_imgs.append (img)
            return img
    return ''    


## handle links..
linkify2 = re.compile(r'\[\[http(://[^ \t]+) +(.*?)\]\]')
linkify1 = re.compile(r'http://([^ \t]+)')
linkify_local = re.compile(r'\[\[([^ \t]+) +(.*?)\]\]')
forbiden_in_fname = re.compile (r'[%\?\!:\'\"\\\(\)\=\& ]+')

spec4win = re.compile(r'<win>(.+?)</win>')
spec4lin = re.compile(r'<lin>(.+?)</lin>')
spec4allos = re.compile(r'<altinfo>(.+?)</altinfo>')

def filter_os(targetos, src):
    rez = src
    if targetos == 'w':  rez = spec4win .sub('\\1', rez) ;     rez = spec4lin .sub('', rez) ;        rez = spec4allos .sub('', rez) ;
    elif targetos == 'l':  rez = spec4win .sub('', rez) ;          rez = spec4lin .sub('\\1', rez) ;   rez = spec4allos .sub('', rez) ;
    else:  rez = spec4win .sub('', rez) ;           rez = spec4lin .sub('', rez) ;        rez = spec4allos .sub('\\1', rez) ;
    return rez

def filter_linkify(src, kmeleon = False):
    rez = src
    #if targetbrowser == 'firefox':
    rez = linkify2.sub('<a href="http_\\1">\\2</a>', rez)
    rez = linkify_local.sub('<a href="\\1">\\2</a>', rez)
    rez = linkify1.sub('<a href="http://\\1">\\1</a>', rez)
    rez = rez.replace('http_', 'http')
    if kmeleon: rez = utilswin.filter_linkify_4kmeleon(rez)
    return rez

def clean_url4fname (url):
    rez = forbiden_in_fname.sub('', url)
    rez = rez.replace('/', '__').strip(' _')
    if rez[0:8] == 'http____': rez = rez[8:]
    return rez


##
##def listofdict_filterkey(listofdict, key):
##    reslist = []
##    for d in listofdict:
##        reslist.append(d[key])
##    return reslist    
##
##
##def sortlist(listofdict, key):
##    n = len(listofdict)
##    for i  in range(n):
##        for j in range(i, n):
##            if listofdict[i][key] > listofdict[i][key]:
##                listofdict[i], listofdict[j] = listofdict[j], listofdict[i]
##    return listofdict    


## map program names to file names on disk
letters_lt    = u'ąčęėįšųūžĄČĘĖĮŠŲŪŽ' 
letters_latin = 'aceeisuuzACEEISUUZ'
def latinize(str):
    ##print str
    for i in range(len(letters_latin)):
        ##print (letters_lt[i], letters_latin[i])
        str = str.replace(letters_lt[i], letters_latin[i])
    str = re.sub('[^\w ()-_]+', '', str)
    str = re.sub('\s+', '-', str)
    ##str = re.sub('[_-]{2,5}', '-', str)
    return str.encode('ascii', 'ignore').strip('- _')
## --------------
