# -*- coding: UTF-8 -*-
###########################################################################
# Eole NG - 2007  
# Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
# Licence CeCill  cf /root/LicenceEole.txt
# eole@ac-dijon.fr 
#  
# rml.py
#  
# Feuille de style de traduction au format TRML et différents mappings
# objets python -> strings trml (http://openreport.org/index.py/trml2pdf)
#       
###########################################################################
from zephir.utils import trml2pdf 
from zephir.config import charset

class RML:
    """Conversion des informations en TRML
    """

    def dump_pdf(self, rml_string):
        """Conversion du rml en pdf
        """
        return trml2pdf.parseString(rml_string)

    def page(self, title="", story=""):
        """Modèle de génération d'une page
        """
        return """<?xml version="1.0" encoding="%s" ?>                                    
<!DOCTYPE document SYSTEM "rml_1_0.dtd">
<document filename="">
<template pageSize="(21cm, 29.7cm)"                                                         
          leftMargin="1.5cm"                                                                
          rightMargin="1.5cm"                                                               
          topMargin="1.5cm"                                                                 
          bottomMargin="1.5cm"                                                              
          showBoundary="1"                                                                  
          allowSplitting="20"                                                               
          >  
<pageTemplate id="main">
  <frame id="first" x1="1.5cm" y1="1.5cm" width="19cm" height="25.5cm"/>
</pageTemplate>
</template>

<stylesheet>

<blockTableStyle id="myBlockTableStyle">                                               
  <blockFont name="Helvetica-BoldOblique" size="10" start="0,0" stop="1,0"/>
  <blockFont name="Courier-Bold" size="10" start="0,1" stop="-1,-1"/>
  <lineStyle kind="GRID" colorName="silver"/>                                       
</blockTableStyle>              

<paraStyle name="bullet" fontName="Helvetica" fontSize="10" leftIndent="10mm" firstLineIndent="-10mm"/>

</stylesheet>
<story>
<title>%s</title>
<spacer length="1cm"/>
%s
</story>
</document>
""" % (charset,title, story)


    def sect(self, title, content):
        """Formatage
        d'une section
        """
        return """<h2>%s</h2> <spacer length="15"/> %s """ % (title, content)

    def page_break(self):
        """Saut de page
        """
        return """<condPageBreak height="200cm"/>"""

    def para(self, s):
        """Formatage
        d'un paragraphe
        """
        return "<para>%s</para>" % str(s)

    def list_to_table(self, list_dict):
        return DictToTable(list_dict)

    def dict_to_list(self, dict):
        return DictToList(dict)

    def list_to_list(self, liste):
        return ListToList(liste)


# mapping types de base python -> formatage html

class DictToTable:
    """Transforme une liste de dictionnaires python
    en un tableau TRML
    """
    def __init__(self, list_dict):
        self.list_dict = list_dict

    def _dict_to_table_row(self, d):
        """Mapping
        dictionnaire python -> table TRML

        exemple
        -------

        {'libelle': 'horus', 'id': 13}

        devient : 

        <tr><td>horus</td><td>13</td></tr>
        """
        l = []
        l.append("<tr>")
        for s in d.values():
            l.append( "<td>%s</td>" % str(s) )
        l.append("</tr>")
        return "".join(l)

    def _dict_to_table_head(self, d):
        """Mapping dictionnaire python -> table head
        """
        l = []
        l.append("<tr>")
        for s in d.keys():
            l.append( "<td>%s</td>" % s )
        l.append("</tr>")    
        return "".join(l)
    
    def list_to_table(self,list_dict):
        """Mapping liste de dictionnaires python -> rml table
        """
        l = ["""<blockTable  style="myBlockTableStyle">"""]
        # renseigne l'en-tête de la table
        l.append(self._dict_to_table_head(list_dict[0]))
        # remplis le tableau
        for d in list_dict:
            l.append(self._dict_to_table_row(d))
        l.append("""</blockTable><spacer length="15"/>""")        
        return "".join(l)

    def __repr__(self):
        return self.list_to_table(self.list_dict)

class DictToList:
    """Transforme un dictionnaire python en liste rml
    """
    def __init__(self, dict):
        self.dict = dict
    
    def _dict_to_list(self,dict):
        """Mapping
        dictionnaire python -> liste RML
        """
        l=[]
        for em,item in dict.items():
            l.append("""<para style="bullet">- <i> %s </i> : %s </para>""" % (em, item) )
        return "".join(l)

    def __repr__(self):
        return self._dict_to_list(self.dict)

class ListToList:
    """Transforme une liste python en une liste RML
    """

    def __init__(self, list):
        self.list = list
    
    def list_to_list(self,list):
        """Mapping
        liste python -> liste RML
        """
        l = []

        for item in list :
            l.append("""<para style="bullet"> - %s </para>""" % item )

        return "".join(l)

    def __repr__(self):
        return self.list_to_list(self.list)
