# -*- 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
#
# services.py
#
# pages web de gestion des services installés
#
###########################################################################
from twisted.web import static
from twisted.web.resource import Resource
from zephir.web.template.design import Design, proxy, get_user
from zephir.web.config import Navigation
from zephir.web.html.erreur import *
from html import escape as html_escape
from zephir.eolerpclib import xmlrpclib


def escape(value):
    if isinstance(value, bytes):
        return value.decode()
    return value


__TODO__ = """

- affichage de la liste des services installés sur un serveur

faire une liste des services correspondant à un serveur,
puis repérer quels sont les services installés.

Repérer le module du serveur considéré
dans la table des services, retirer la liste des services du module
ensuite, faire un diff services * services_installes

"""

class Services(Design):
    """Ressource conteneur services
    """
    def __init__(self, *args, **kwargs):
        self.entites = {
            'add':AddService()
            ,'add2':AddService2()
            ,'get':GetService()
            ,'edit':EditServiceDesc()
            ,'edit2':EditServiceIns()
            ,'del':DelService()
            ,'deleted':DeletedService()
            }
        super().__init__(*args, **kwargs)

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        name = name.decode()
        if name in self.entites:
            return self.entites[name]()
        return self

    def wmfactory_title(self,request):
        return "(%s) Services" % get_user(request)

    def wmfactory_content(self, request):
        """Aucun contenu :
        l'utilisateur n'est pas sensé aller là
        """
        return ""

## """
## <a href="service/add">Ajout d'un service</a>
## <br/>
## <a href="service/get">Affichage de la liste des services</a>
## <br/>
## <a href="service/del">Suppression d'un service</a>
## """

class AddService(Design):
    """Ajout d'un service **page 1**
    """
    isLeaf = True
    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"add" :
            return self
        return Services()

    def wmfactory_title(self,request):
        return "(%s) Nouveau service" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def _dump_html(self,id) :
        return """
<h1>Entrez le libellé du service</h1>
<FORM METHOD=POST ACTION="add2">
<table cellpadding="15" cellspacing="0" align="center" valign="middle" >
<tr><td> Service :</td><td>
<input type=text size=8 name="libelle" value=""></td></tr>
<input type="hidden" name="id" value="%s">
<tr><td><INPUT type=SUBMIT value="Ok"></td>
<td><input name="annuler" value="ANNULER" type="reset" /></td>
</tr>
<tr><td colspan="2" align="center">
<a href="/module/get">Liste des modules</a>
</td></tr>
</table>
</form>
""" % id


    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
                self.content = self._dump_html(id)
            except :
                raise FrontendError("identifiant")

        except Exception as e:
            self.content = e

        return self.content

class AddService2(Design):
    """Ajout d'un service
    """
    isLeaf = True

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"add2" :
            return self
        return Service()

    def wmfactory_title(self,request):
        return "(%s) Service (ajout)" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
                libelle = escape(request.args[b'libelle'][0])
            except:
                raise FrontendError("identifiant ou libelle")

            try:
                liste = backend(proxy(request)(request).services.add_service(id,u(libelle)))
                self.content = """
                <p>Le service <b>%s</b>a bien été ajouté<br>
                avec la clef : <b>%s</b><br/>
                <a href="/module/get">Liste des modules</a><br/></p>
                """ % (libelle,liste)

            except xmlrpclib.ProtocolError:
                raise BackendError("""Vous n'êtes pas autorisé à effectuer cette action""")
            except :
                raise BackendError

        except Exception as e:
            self.content = e
        return self.content


class GetService(Design):
    """Récupération de la liste des services pour un module
    """
    isLeaf = True

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"get" :
            return self
        return Services()

    def wmfactory_title(self,request):
        return "(%s) Liste des services" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def _dump_html(self,liste):
        """Affichage de la liste des services
        """
        s = """<table cellpadding="1" cellspacing="2"><tr><td>libellé</td><td>clef</td></tr>"""
        for d in liste:
            modele = """
            <tr><td>%(libelle)s</td><td>%(id)s</td>
            <td><a href="edit?id=%(id)s">modifier</a></td>
            <td><a href="del?id=%(id)s">supprimer</a></td>
            </tr>
            """ % d
            s += modele

        s += "</table>"
        return s

    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
            except:
                raise FrontendError("identifiant")
            try:
                liste = backend(proxy(request)(request).services.get_service_module(id))
                if liste == [] :
                    self.content = """<h1>Il n'y a aucun service sur ce module</h1>
                    <p><a href="/services/add?id=%s">Ajouter un service à ce module</a><br/>
                    <a href="/module">Retour à la liste des modules</a></p>
                    """ % id
                else :
                    self.content = """<h1>Liste des services du module : %s</h1>%s
            <p><a href="/services/add?id=%s">Ajouter un service à ce module</a><br/>
            <a href="/module">Retour à la liste des modules</a></p>
                    """ % (id, self._dump_html(liste),id)
            except xmlrpclib.ProtocolError:
                raise BackendError("""Vous n'êtes pas autorisé à effectuer cette action""")
            except :
                raise BackendError

        except Exception as e:
            self.content = e
        return self.content

class EditServiceDesc(Design):
    """Edition (modification) d'un service
    """

    isLeaf = True

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"edit" :
            return self
        return Services()

    def wmfactory_title(self,request):
        return "(%s) Service (Edition)" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def _dump_html(self,id,libelle):
        """Formulaire d'edition du service
        """
        return """
<h1>Entrez le nouveau descriptif du service</h1>
<FORM METHOD=POST ACTION="edit2">
<table cellpadding="15" cellspacing="0" align="center" valign="middle" >
<tr><td>Libellé</td><td>
<input type=text size=10 name="libelle" value="%s"></td></tr>
<tr><td algin="right">
<input type="hidden" name="id" value="%s">
<INPUT type=SUBMIT value="Ok">
</td></tr>
</table>
</form>
""" % (libelle,id)


    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
                id = int(id)
            except:
                raise FrontendError("identifiant")

            try:
                resultat = backend(proxy(request)(request).services.get_service(id))
                d = resultat[0]
                self.content = self._dump_html(d['id'],d['libelle'])
            except xmlrpclib.ProtocolError:
                raise BackendError("""Vous n'êtes pas autorisé à effectuer cette action""")
            except :
                raise BackendError

        except Exception as e:
            self.content = e

        return self.content



class EditServiceIns(Design):
    """Edition d'un service, update du backend
    """
    isLeaf = True

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"edit2" :
            return self
        return Services()

    def wmfactory_title(self,request):
        return "(%s) Service (Edition)" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
                libelle = escape(request.args[b'libelle'][0])
            except:
                raise FrontendError("identifiant ou libelle")
            try:
                resultat = backend(proxy(request)(request).services.edit_service(id,u({'libelle':libelle})))
                service = backend(proxy(request)(request).services.get_service(id))[0]

                self.content = """
                <p>Le service %s a bien été modifié<br/>
                <a href="/services/get?id=%s">Retour à la liste des services du module</a></p>
                """ % (libelle, service['module'])
            except xmlrpclib.ProtocolError:
                raise BackendError("""Vous n'êtes pas autorisé à effectuer cette action""")
            except:
                raise BackendError

        except Exception as e:
            self.content = e

        return self.content


class DelService(Design):
    """Confirmation de suppression d'un service
    """
    isLeaf = True

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"del" :
            return self
        return Services()

    def wmfactory_title(self,request):
        return "(%s) Service (Suppression)" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
            except:
                raise FrontendError("identifiant")

            self.content = """
            <p>Voulez-vous vraiment supprimer le service %s ?<br/>
            <a href="deleted?id=%s">Suppression</a><br/>
            <a href="/module/get">annuler</a>
            </p>
            """ % (id,id)

        except Exception as e:
            self.content = e

        return self.content

class DeletedService(Design):
    """Suppression effective d'un service
    """
    isLeaf = True

    def getChild(self, name, request):
        if static.isDangerous(name):
            return static.dangerousPathError
        if name == b"deleted" :
            return self
        return Services()

    def wmfactory_title(self,request):
        return "(%s) Service (Suppression)" % get_user(request)

    def wmfactory_content(self, request):
        return self.content

    def renderView(self, request):
        try:
            try:
                id = escape(request.args[b'id'][0])
            except:
                raise FrontendError("identifiant")

            try:
                backend(proxy(request)(request).services.del_service(id))
                self.content = """
                <p>Le service a bien été supprimé<br/></p>
                <a href="/module">Retour à la page des modules</a><br/>
                """
            except DatabaseError as e:
                raise BackendError("Veuillez vérifier que le service que vous essayer de supprimer n'est pas en cours d'utilisation")
            except xmlrpclib.ProtocolError:
                raise BackendError("""Vous n'êtes pas autorisé à effectuer cette action""")
            except :
                raise BackendError

        except Exception as e:
            self.content = e

        return self.content


## class ServicesInstalles(Design):
##     """
##     Formulaire de renseignements concernant les services (actifs ou non)
##     """

##     def _services_disponibles(self, id_module) :
##         """Liste des services disponibles pour le module considéré
##         """
##         modules = proxy(request)(request).modules.get_module(id_module)
##         return modules

##     def _services_installes(self) :
##         """Liste des services effectivements installés sur un serveur
##         """
##         pass

##     def wmfactory_title(self,request):
##         return "Nouveau service"

##     def wmfactory_content(self, request):
##         # FIXME
##         # self.id_module = escape(request.args[b'id_module'][0])
##         self.id_module = 1
##         return proxy(request)(request).serveurs.get_serveur()
##         # return self._services_disponibles(1)


## ##         return """
## ## <p># FIXME il vaut mieux proposer la liste des modules</p>
## ## <h1><center>Entrez l'identifiant du module</h1><br>
## ## <FORM METHOD=POST ACTION="/service">
## ## <table cellpadding="15" cellspacing="0" align="center" valign="middle" >
## ## <tr><td>Identifiant</td><td>
## ## <input type=text size=10 name="id" value=""></td></tr>
## ## <tr><td algin="right">
## ## <INPUT type=SUBMIT value="OK">
## ## </td></tr>
## ## </table>
## ## </form>
## ## """

##     def getChild(self, name, request):
##         # Protect against malicious URLs like '..'
##         if static.isDangerous(name):
##             return static.dangerousPathError
##         if name == b"maj":
##             return MajServicesInstalles()
##         return self

##     def renderView(self, request):
##         return self.content


## class MajServicesInstalles(Design):
##     # FIXME
##     isLeaf = True

##     def initialize(self,*args ,**kwargs):
##         self.error_message = ""

##     def _options(self, types):
##         l = []
##         for type in types.items() :
##             value , libelle = type
##             s = """<OPTION VALUE="%s">%s</OPTION>""" % (value, libelle)
##             l.append(s)
##         return "\n".join(l)

##     def _hidden(self, rne):
##         return """<input type="hidden" name="rne" value="%s"/> """ % rne

##     def formulaire(self, rne, rne_form, option_list):
##         if self.error_message != "":
##             sortie = self.error_message
##             self.error_message = ""
##             return sortie
##         else:
##             formulaire = """
## <h1>Remplissez/modifiez les champs décrivant l'établissement</h1>
## <FORM METHOD=POST ACTION="/description">
## <table cellpadding="5" cellspacing="0" align="center" valign="middle"
## width="80%"><tr><td>R.N.E. </td><td> %s </td></tr> %s <tr><td>nom du site</td><td><input type="text" size=30 name="libelle" value=""></td></tr>
## <tr><td>adresse</td><td><textarea rows="2" cols="30" name="adresse"></textarea></td></tr>
## <tr><td>téléphone</td><td><input type="text" size="12" name="telephone" value=""></td></tr>
## <tr><td>fax</td><td><input type="text" size="12" name="fax" value=""></td></tr>
## <tr><td>adresse mail</td><td><input type="text" size="20" name="mail" value=""></td></tr>
## <tr><td>responsable</td><td><input type="text" size="20" name="responsable" value=""></td></tr>
## <tr><td>remarques</td><td><textarea rows="3" cols="30" name="remarques"></textarea></td></tr>
## <tr><td>type d'établissement</td><td>
## <SELECT NAME="type"><OPTION SELECTED VALUE="0"></OPTION> %s </SELECT></td></tr></table><br><CENTER><INPUT type="SUBMIT" value="OK"></CENTER></form>"""

##             return formulaire % (rne, rne_form, option_list)

##     def wmfactory_title(self,request):
##         return "Nouvelle variante"

##     def wmfactory_content(self, request):
##         return self.formulaire(self.rne, self._hidden(self.rne), self._options(types))

##     def renderView(self, request):
##         self.rne = escape(request.args[b'rne'][0])
##         if not self.rne :
##              self.error_message = """
##         <p>vous n'avez pas renseigné le numéro R.N.E.<br>
##         <a href="javascript:history.back()">Retour</a></p>
##         """
##         else:
##             if proxy(request)(request).etabs.get_etab(self.rne) != []:
##                 self.error_message =  """
##         <p>Ajout impossible, cet établissement existe déjà !<br>
##         <a href="javascript:history.back()">Retour</a></p>
##         """

##         return self.content
