#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#-----------------------------------------------------------------------------
import sys, string, re, os, codecs

__rel_lib_path__ = ('lib/python',)   #  relative library path
__parent_dir__ = ''                  #  python scripts installation directory

def _libpathAdjust (libPaths):
    global __parent_dir__
    script_dir = os.path.dirname (sys.argv[0])
    if len (script_dir) == 0:     script_dir = '.'
    if script_dir[0] != "/":
        script_dir = os.path.abspath(script_dir)
    __parent_dir__ = os.path.dirname (script_dir)
    for lp in libPaths:
        newPath = os.path.join (__parent_dir__, lp)
        if os.path.isdir (newPath):
            if newPath not in sys.path:
                sys.path.insert(0, newPath)
        else:
            print ("ERROR: Additionnal library path not exists\n\t[%s]"
                   % newPath)
    # -------------------------------------------------- _libpathAdjust()

if __rel_lib_path__:
    _libpathAdjust (__rel_lib_path__)

#
#   The path is adjusted, we can make all imports
#
from StringIO import StringIO
from Xtmpl import Xtmpl
from UF import UF

#
#   define the used directories and files
#
base_dir = os.path.dirname (os.path.dirname (__parent_dir__))
data_dir = os.path.join (base_dir, 'admin', 'xml-data')
tmpl = os.path.join (data_dir, 'generique.xtpl')
extra_root = base_dir
intra_root = os.path.join (base_dir, 'etud')
admin_root = os.path.join (base_dir, 'ens')

crs_data_dir = os.path.join (data_dir, 'cours')
extra_dir = os.path.join (extra_root, 'cours')
intra_dir = os.path.join (intra_root, 'cours')
admin_dir = os.path.join (admin_root, 'cours')

composantes = {
   'AP':   '01.0',
   'ASR':  '02.0',
   'OMGL': '03.0', 
   'MATH': '04.0', 
   'EOG':  '05.0', 
   'ANG':  '06.0', 
   'TEX':  '06.0', 
   'SYN':  '07.0'
   }

def get_num_menu(key):
    """compute the menu index if the fiche from the key
    """
    pre = key[:-1]
    num = key[-1]
    ## print pre, num
    if pre == 'TEX':
        num = repr(int(num) + 5)
    return composantes[pre] + num
    # ----------------------------------------------------------- get_num_menu()
    
def get_out_file(id, dir):
    """get the output file name, 'None' if destination file exists already.
    """
    out_file = os.path.join (dir, "%s.htm" % id)
##    out_file = os.path.join (dir, "%s_%s.html" %
##                             (stab['{id}'], stab['{date}']))
##    if os.path.exists (out_file):
##	print "\t'%s' dj trait" % stab['{id}']
##	out_file = None
    return out_file
    # ----------------------------------------------------------- getOutFile()

def copy_file(ifile, ofile):
    """Make a simple file copy
    """
    fin = open (ifile, 'r')
    txt = fin.read()
    fin.close()
    fout = open (ofile, 'w')
    fout.write (txt)
    fout.close()
    # ------------------------------------------------------------ copy_file()

def apply_template(tmpl_file, title, path, menu, txt):
    """Use a XTPL template to generate an HTML file.
    """
    xtpl = Xtmpl(tmpl_file)
    xtpl.init_subst()
    xtpl.add_subst ('TEXT', txt)
    xtpl.add_subst ('TITLE', title)
    xtpl.add_subst ('PATH', path)
    xtpl.add_subst ('MENU', menu)
    return xtpl.apply_template()
    # ------------------------------------------------------- apply_template()

def build_fiche(col, key, ofile, mode):
    ## print ofile
    bi = col.get_basic_info (key)
    link = u"""<a href="index.html">
    <img src="../../img/top.png" alt="Up" /></a>
    """
    path = "../.."
    
    title = u"%s : %s" % (bi['code'], bi['titre'])
    mention = u"UBS -- IUT de Vannes -- Dpartement Informatique"
    if mode == 'etud':
	txt = col.mk_html_etud(key)
        menu = '00.03.02.' + get_num_menu(key)
    else:
	txt = col.mk_html_extra(key)
        menu = '00.03.02.' + get_num_menu(key)
    txt = apply_template(tmpl, title, path, menu, txt).encode('iso-8859-15')
    fout = open (ofile, 'w')
    fout.write (txt)
    fout.close()
    ## print "\t'%s' written" % os.path.basename (ofile)
    # ---------------------------------------------------------- build_fiche()

def build_index(uecol):
    buf = StringIO()
    for key in uecol.get_keys():
	buf.write (uecol.mk_html_sec_index(key))
    return buf.getvalue()
    # ---------------------------------------------------------- build_index()

def main():
    """The main routine
    """
    ##mention = sys.argv[2]  ## #2 car le script est lanc via 'launch' !!
    ##print mention, crs_data_dir

    uecol = UF(os.path.join(crs_data_dir, 'uf.xml'))
    #
    #  first step: create the "fiches"
    #
    for key in uecol.get_keys():
	file = get_out_file(key, intra_dir)
	if file:
            build_fiche(uecol, key, file, 'etud')
##	file = get_out_file(key, extra_dir)
##	if file:
##            build_fiche(uecol, key, file, 'extra', mention)
##    cscol = uecol.cours
##    for key in cscol.get_keys():
##	file = get_out_file(key, extra_dir)
##	if file:
##            build_fiche(cscol, key, file, 'extra')
##	file = get_out_file(key, intra_dir)
##	if file:
##            build_fiche(cscol, key, file, 'etud')
##    print "\tFiches cres dans '%s'\n\tet '%s'\n" % (extra_dir, intra_dir)
    print "\tFiches cres dans '%s'<br />\n" % intra_dir

    #
    #  second step: create the index files
    #
    txt = build_index(uecol)
    menu = '00.03.02'
    path = "../.."
    title = "Index dtaill des UF du DUT Informatique"
    txt = apply_template(tmpl, title, path, menu, txt)

    ofile1 = get_out_file('idx_cours', intra_dir)
    fout = open(ofile1, 'w')
    fout.write(txt)
    fout.close()
    print "\tFichier '%s' cre<br />" % ofile1.replace(base_dir, '')
##    ofile2 = get_out_file('idx_cours', extra_dir)
##    copy_file(ofile1, ofile2)
##    print "\tFichier '%s' cre" % ofile2.replace(base_dir, '')

    #
    #  last step mark the timestamp
    #
    ttfile = os.path.join(crs_data_dir, 'timestamp')
    fout = open(ttfile, 'w')
    fout.write('')
    fout.close()
    
    # ----------------------------------------------------------------- main()


main()
