# coding=UTF-8
# -*- coding: UTF-8 -*-

import string, re
import os as oslib
import codecs
import pprint
import utilswin

from genshi.template import TemplateLoader
from genshi.core import Stream
from genshi.output import encode, get_serializer
from genshi.output import DocType
dirname_ = oslib.path.dirname(__file__)
templates_path = oslib.path.join(dirname_, 'templates/')
print templates_path
loader = TemplateLoader( templates_path )
template = loader.load('main.html')


        rawfiles = oslib.listdir('raw_content/%s/' % targetlang) 
        if targetlang == 'lt': rawfiles  += map(lambda x:  '_detaliau/' + x, oslib.listdir('raw_content/%s/_detaliau/' % targetlang))
        rawfiles = [ f for f in rawfiles if f[-4:] == 'html'] 
        ##os.path.walk('raw_content', callback_scan, r'.*\.html')
        pagenr = 0
        for fname in rawfiles:
            fname = fname.replace('\\', '/')
            pagename = fname.split('/')[-1] 
            pagename = pagename[:-5]
            print fname
            
            rawhtml = mylibs.getftext('raw_content/'+targetlang+'/'+fname)        
            if fname.find('_detaliau')>-1:
                no_lch = re.compile(r'<a href=\".+?\.lch\">.+?</a>')
                rawhtml = no_lch.sub( "", rawhtml)
            
            page = dict(zip(config.pagenames,  config.pages)).get(pagename, '')
            title_current = pagename_titles.get(pagename, '')
            stream = template.generate(\
                   rawhtml = rawhtml.decode("UTF-8"), \
                   programs = [], \
                   categories = [], \
                   items = config.pagenames,\
                   titles = config.menus[targetlang],\
                   maintitle = config.maintitles[targetlang],\
                   title_current = title_current, \
                   pagename_current = pagename,\
                   pagename_titles = pagename_titles, \
                   pageid = None, \
                   targetos = targetos, \
                   category_progs_counts = [], \
                   category_sizes = [], \
                   category_sizes_cumulative=[]
                   
                   #_catname_list=_catname_list\
                   )
             
            
            
            html = stream.render(method='xhtml')
    ##        encode(generator, method=method, encoding=encoding)
    ## http://mail.mems-exchange.org/durusmail/quixote-users/3414/
            
            if targetos=='l':
                no_doctype_4gtkhtml = re.compile(r'<\!DOCTYPE [^>]+?>')
                html = no_doctype_4gtkhtml.sub( "", html)
                
           
            pagepath = config.html_root_rel2generator + config.oshtmldirs[targetos] +langpart +pagename+'.html'
            mylibs.putftext(pagepath , html)
            print "==%s== %s"  % (pagename, fname)
