# -*- coding: utf-8 -*-
from twisted.web import resource, static
import cgi, logging
from nevow import inevow, rend, tags, loaders, flat
import os, sys
import formal
from formal import iformal
from webgui import GenericFormalResponsePage, Translator
from utils import validators, mail, pwgen
from zope.interface import implements
from twisted.internet import defer
from Database import utils as dbutils
import base64, pickle

log = logging.getLogger("Webgui")
curdir=os.path.abspath(os.path.dirname(sys.argv[0]))
template_path = curdir+'/Web/html/Admin/'

class Menu(rend.Fragment):

   docFactory = loaders.xmlfile('userlist_Menu.html', templateDir=template_path)


class Refresh(rend.Page):

   def __init__(self, target):
      self.target = target
      rend.Page.__init__(self)

   def renderHTTP(self, ctx):
      request = inevow.IRequest(ctx)
      log.debug("REFRESH TO %s" % self.target)
      request.setHeader('Location', self.target)
      request.setResponseCode(302)
      return 'Refreshing...'


   def childFactory(self, ctx, data):
      request = inevow.IRequest(ctx)
      log.debug("REFRESH TO %s" % self.target)
      request.setHeader('Location', self.target)
      request.setResponseCode(302)
      return 'Refreshing...'


class RefreshPost(rend.Page):

   def __init__(self, target, postdata):
      self.target = target
      self.postdata = postdata
      rend.Page.__init__(self)

   def renderHTTP(self, ctx):
      log.debug("REFRESHPOST TO %s" % self.target)
      return Refresh(self.target+'/?postdata='+self.postdata)


   def childFactory(self, ctx, data):
      log.debug("REFRESHPOST TO %s" % self.target)
      return Refresh(self.target+'/?postdata='+self.postdata)


class UserDettails(formal.ResourceMixin, rend.Page, Translator):

   addSlash=True
   docFactory = loaders.xmlfile('userlist_Registered_Dettails.html', templateDir=template_path)

   def __init__(self, parent, udata, uuid):
      self.parent = parent
      self.uuid = uuid
      self.udata = udata
      self.newsubs  = {}
      self.newhours = {}
      self.newmonths = {}
      self.formsubmitted = False
      self.childFactoryDenied = self.parent.childFactoryDenied
      self.render_HEADER = self.parent.render_HEADER
      self.render_FOOTER = self.parent.render_FOOTER
      self.render_HEAD = self.parent.render_HEAD
      self.render_Menu = self.parent.render_Menu
      formal.ResourceMixin.__init__(self)
      rend.Page.__init__(self)

   def render_ihavedata(self, ctx, data):
      if len(self.newsubs) > 0:
         # Nuova sottoscrizione
         if 'newsubscription' in self.newsubs:
            user=self.udata.username
            sub = str(self.newsubs['newsubscription'])
            dbutils.addSubscription(user, sub)
      if len(self.newhours) > 0:
         if 'newHours' in self.newhours:
            log.debug("Add new Hours")
            user=self.udata.username
            h = str(self.newhours['newHours'])
            hm =  int(self.newhours['howmany'])
            dbutils.addNewHours(user, h, hm)
      if len(self.newmonths) > 0:
         if 'newMonths' in self.newmonths:
            log.debug("Add new Mountly Hours")
            user=self.udata.username
            h = str(self.newmonths['newMonths'])
            hm =  int(self.newmonths['howmany'])
            dbutils.addNewMonths(user, h, hm)
      return ' '

   def form_hourdetails(self, ctx):
      
      hourst = dbutils.getHourTypes()
      hourtypes = []
      for hour in hourst:
         hourtypes.append((hour.name, hour.name))

      form = formal.Form()
      form.addField('newHours', formal.String(strip=True, required=True),
                         formal.widgetFactory(formal.SelectChoice, options=hourtypes,
                                 noneOption=None), label="Tipo")

      #form.addField('howmany', formal.Integer(required=True), label='Quantita\'')
      form.addField('howmany', formal.String(strip=True, required=True),
                         formal.widgetFactory(formal.SelectChoice, options=map(lambda a: (a, a) , range(1, 101)),
                                 noneOption=None), label="Quantita\'")

      form.addAction(self.submitted_hours, label='Aggiungi')
      form.data = self.newhours
      return form


   def form_monthdetails(self, ctx):

      hourst = dbutils.getHourTypes()
      hourtypes = []
      for hour in hourst:
         hourtypes.append((hour.name, hour.name))

      form = formal.Form()
      form.addField('newMonths', formal.String(strip=True, required=True),
                         formal.widgetFactory(formal.SelectChoice, options=hourtypes,
                                 noneOption=None), label="Tipo")
   
      #form.addField('howmany', formal.Integer(required=True), label='Quantita\'')
      form.addField('howmany', formal.String(strip=True, required=True),
                         formal.widgetFactory(formal.SelectChoice, options=map(lambda a: (a, a) , range(1, 101)),
                                 noneOption=None), label="Quantita\'")

      form.addAction(self.submitted_months, label='Aggiungi')
      form.data = self.newmonths
      return form


   def form_subdetails(self, ctx):

      subst = dbutils.getSubsTypes()
      subscriptions = []
      for stype in subst:
         subscriptions.append((stype.name, stype.name))

      form = formal.Form()
      form.addField('newsubscription', formal.String(strip=True, required=True),
                        formal.widgetFactory(formal.SelectChoice, options=subscriptions,
                                          noneOption=None), label="Tipo")

      form.addAction(self.submitted_hours, label='Aggiungi')
      form.data = self.newsubs
      return form

   def submitted_hours(self, ctx, form, data):
      # XXX this is a very bad hack
      request = inevow.IRequest(ctx)
      request.method = "GET"

      if not self.formsubmitted:
         self.formsubmitted = True
         self.newhours = data
         return self
      else:
         self.formsubmitted = False

   def submitted_months(self, ctx, form, data):
      # XXX this is a very bad hack
      request = inevow.IRequest(ctx)
      request.method = "GET"

      if not self.formsubmitted:
         self.formsubmitted = True
         self.newmonths = data
         return self
      else:
         self.formsubmitted = False


   def submitted_subs(self, ctx, form, data):
      # XXX this is a very bad hack
      request = inevow.IRequest(ctx)
      request.method = "GET"

      if not self.formsubmitted:
         self.formsubmitted = True
         self.newsubs = data
         return self
      else:
         self.formsubmitted = False

   def child_delabili(self, ctx):
      childctx=inevow.IRemainingSegments(ctx)
      if len(childctx) == 2:
         log.debug("REMOVING subscription %s for USER %s" % (childctx[1], self.udata.username) )
         dbutils.delSubscription(self.udata.username, childctx[1])
      refresh="/".join(inevow.ICurrentSegments(ctx))
      return Refresh("/"+refresh)

   def child_delmonths(self, ctx):
      childctx=inevow.IRemainingSegments(ctx)
      if len(childctx) == 2:
         log.debug("REMOVING MountlyHours %s for USER %s" % (childctx[1], self.udata.username) )
         dbutils.delMontlyHours(self.udata.username, childctx[1])
      refresh="/".join(inevow.ICurrentSegments(ctx))
      return Refresh("/"+refresh)

   def child_delhours(self, ctx):
      childctx=inevow.IRemainingSegments(ctx)
      if len(childctx) == 2:
         log.debug("REMOVING UserHours %s for USER %s" % (childctx[1], self.udata.username) )
         dbutils.delUserHours(self.udata.username, childctx[1])
      refresh="/".join(inevow.ICurrentSegments(ctx))
      return Refresh("/"+refresh)

   def child_updateuser(self, ctx):
      request = inevow.IRequest(ctx)
      if request.method == 'POST':
         log.debug("POST updateUser")
         try:
         #if True:
            if request.args["Aggiorna"][0] == 'Aggiorna':
               log.debug("Aggiornamento utente %s" % (self.udata.username))
               email = request.args['email'][0]
               password = request.args['password'][0]
               nome = request.args['nome'][0]
               cognome = request.args['cognome'][0]
               citta = request.args['citta'][0]
               mlist = request.args['mlist'][0]
               dbutils.updateUserDetails(self.udata.username, password, nome, cognome, citta, email, mlist)

         except:
            pass

      childctx=inevow.IRemainingSegments(ctx)
      refresh="/".join(inevow.ICurrentSegments(ctx))
      return Refresh("/"+refresh)



   def render_getDetails(self, ctx, data):
      #return tags.directive("form userdetails")
      try:
         iscr = self.udata.tsiscrizione.asHumanly()
      except:
         iscr = 'Sconosciuta'

      try:
         llogin = self.udata.lastlogin.asHumanly()
      except:
         llogin = 'Mai'

      subs = list(dbutils.getSubscriptions(self.udata.username))
      substags = []
      for sub in subs:
         try:
            exp = sub.expiration.asHumanly()
         except:
            exp = 'Mai'

         rsub = tags.tr[
                   tags.td(style="border: 1px solid #000;")[sub.subname],
                   tags.td(style="border: 1px solid #000;")[exp],
                   tags.td(style="border: 1px solid #000")[
                      tags.a(href="/userlist/registered/dett/"+self.udata.uniqueid+"/delabili/"+sub.subname,
                         style="text-decoration:none; background: #99ccff",
                         onClick="return confirm('Sicuro?');")['elimina']
                   ]
                ]
         substags.append(rsub)

      hours = list(dbutils.getHours(self.udata.username))
      hourstags = []
      for hour in hours:
         rsub = tags.tr[
                   tags.td(style="border: 1px solid #000;")[hour.hours],
                   tags.td(style="border: 1px solid #000;")[hour.hourstype],
                   tags.td(style="border: 1px solid #000")[
                      tags.a(href="/userlist/registered/dett/"+self.udata.uniqueid+"/delhours/"+hour.hourstype,
                         style="text-decoration:none; background: #99ccff",
                         onClick="return confirm('Sicuro?');")['elimina']
                   ]
                ]
         hourstags.append(rsub)
      
      months = list(dbutils.getMountlyHours(self.udata.username))
      monthstags = []
      for month in months:
         rsub = tags.tr[
                   tags.td(style="border: 1px solid #000;")[month.howmany],
                   tags.td(style="border: 1px solid #000;")[month.hourstype],
                   tags.td(style="border: 1px solid #000")[
                      tags.a(href="/userlist/registered/dett/"+self.udata.uniqueid+"/delmonths/"+month.hourstype,
                         style="text-decoration:none; background: #99ccff",
                         onClick="return confirm('Sicuro?');")['elimina']
                   ]
                ]
         monthstags.append(rsub)

                  
      if self.udata.mlist:
         mlistopts = tags.select(name='mlist')[
                        tags.option(value='yes', selected='selected')['yes'],
                        tags.option(value='no')['no'],
                     ]
      else:
         mlistopts = tags.select(name='mlist')[
                        tags.option(value='yes')['yes'],
                        tags.option(value='no', selected='selected')['no'],
                     ]



      result = tags.table(style="border: 1px solid #000")[
                  tags.tr[
                     tags.td(align="center",
                        style="border: 1px solid #000; background-color: #CCFF00")[
                           tags.b["DETTAGLIO UTENTE %s" % unicode(self.udata.username).encode('iso-8859-16', 'ignore')]
                        ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[tags.form(
                              action="/userlist/registered/dett/"+self.udata.uniqueid+"/updateuser",
                              method="POST")[
                           tags.tr[
                              tags.td[tags.b["Password:"]],
                              tags.td[
                                 tags.input(type='text', name='password', value=unicode(
                                    self.udata.password).encode('iso-8859-16', 'ignore'))
                              ],
                           ],
                           tags.tr[
                              tags.td[tags.b["Nome:"]],
                              tags.td[
                                 tags.input(type='text', name='nome', value=unicode(
                                    self.udata.nome).encode('iso-8859-16', 'ignore'))
                              ],
                           ],
                           tags.tr[
                              tags.td[tags.b["Cognome:"]],
                              tags.td[
                                 tags.input(type='text', name='cognome', value=unicode(
                                    self.udata.cognome).encode('iso-8859-16', 'ignore'))
                              ],
                           ],
                           tags.tr[
                              tags.td[tags.b["Citta':"]],
                              tags.td[
                                 tags.input(type='text', name='citta', value=unicode(
                                    self.udata.citta).encode('iso-8859-16', 'ignore'))
                              ],
                           ],
                           tags.tr[
                              tags.td[tags.b["Nazione:"]],
                              tags.td[unicode(self.udata.nazione).encode('iso-8859-16', 'ignore')],
                           ],
                           tags.tr[
                              tags.td[tags.b["Lingua:"]],
                              tags.td[unicode(self.udata.lingua)],
                           ],
                           tags.tr[
                              tags.td[tags.b["Email:"]],
                              tags.td[
                                 tags.input(type='text', name='email', value=unicode(self.udata.email))
                                
                              ],

                           ],
                           tags.tr[
                              tags.td[tags.b["Newsletter:"]],
                              tags.td[
                                 mlistopts,

                              ],

                           ],

                           tags.tr[
                              tags.td[tags.b["Vorrebbe osservare:"]],
                              tags.td[unicode(self.udata.preferenza).encode('iso-8859-16', 'ignore')],
                           ],
                           tags.tr[
                              tags.td[tags.b["Data iscrizione:"]],
                              tags.td[unicode(iscr)],
                           ],
                           tags.tr[
                              tags.td[tags.b["Ultimo Login:"]],
                              tags.td[unicode(llogin)],
                           ],
                           tags.tr[
                              tags.td(colspan="2")[
                                 tags.input(type='submit', name="Aggiorna", value="Aggiorna")
                              ]
                           ],
                        ]]
                     ]
                  ],
                  tags.tr[
                     tags.td(align="center",
                        style="border: 1px solid #000; background-color: #CCFF00")[
                           tags.b["ABILITAZIONI"]
                        ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[
                           tags.tr[
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b['ABILITAZIONE']],
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b['SCADENZA']],
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b[' ']],
                           ],
                           substags
                        ]
                     ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[
                           tags.tr[
                              tags.td[
                                 tags.directive("form subdetails")
                              ]
                           ]
                        ]
                     ]
                  ],


                  tags.tr[
                     tags.td(align="center",
                        style="border: 1px solid #000; background-color: #CCFF00")[
                           tags.b["ORE RIMANENTI"]
                        ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[
                           tags.tr[
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b['ORE']],
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b['TIPO ORE']],
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b[' ']],
                           ],
                           hourstags
                        ]
                     ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[
                           tags.tr[
                              tags.td[
                                 tags.directive("form hourdetails")
                              ]
                           ]
                        ]
                     ]
                  ],

                  tags.tr[
                     tags.td(align="center",
                        style="border: 1px solid #000; background-color: #CCFF00")[
                           tags.b["ORE AUTORICARICHE MENSILI"]
                        ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[
                           tags.tr[
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b['ORE']],
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b['TIPO ORE']],
                              tags.td(style="border: 1px solid #000; background-color: #E0E0E0")[tags.b[' ']],
                           ],
                           monthstags
                        ]
                     ]
                  ],
                  tags.tr[
                     tags.td[
                        tags.table[
                           tags.tr[
                              tags.td[
                                 tags.directive("form monthdetails")
                              ]
                           ]
                        ]
                     ]
                  ]

               ]
      return result




class Dettails(rend.Page):

   addSlash=True

   def __init__(self, parent):
      self.parent = parent
      self.childFactoryDenied = self.parent.childFactory
      self.render_HEADER = self.parent.render_HEADER
      self.render_FOOTER = self.parent.render_FOOTER
      self.render_HEAD = self.parent.render_HEAD
      self.render_Menu = self.parent.render_Menu
      rend.Page.__init__(self)


   def childFactory(self, ctx, data):
      log.debug("Dettails for UUID: %s" % str(data))
      udata=dbutils.getUserFromUUID(data)
      log.debug("RETURNED: %s" % str(udata))
      if udata:
         return UserDettails(self, udata, data)

      return self.childFactoryDenied(ctx, data)



class Subscribed(rend.Page):

   addSlash=True
   docFactory = loaders.xmlfile('userlist_Subscribed.html', templateDir=template_path)


   def child_dett(self, ctx):
      return Dettails(self)


   def __init__(self, parent):
      self.parent = parent
      self.childFactory = self.parent.childFactory
      self.render_HEADER = self.parent.render_HEADER
      self.render_FOOTER = self.parent.render_FOOTER
      self.render_HEAD = self.parent.render_HEAD
      self.render_Menu = self.parent.render_Menu
      rend.Page.__init__(self)

   def render_SubList(self, ctx, data):
      users = dbutils.getSubscribed()
      log.debug(users)
      try:
         if len(users) > 0:
            res = [tags.tr[
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['USERNAME']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['NOME']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['COGNOME']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['EMAIL']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['ABBONAMENTO']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['SCADENZA']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['LINGUA']],
               tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b[' ']],
               ]
            ]
            for user in users:
               try:
                  exp = user[0].expiration.asHumanly()
               except:
                  exp = 'MAI'
               ures = tags.tr[
                     tags.td(style="border: 1px solid #000")[user[1].username],
                     tags.td(style="border: 1px solid #000")[user[1].nome],
                     tags.td(style="border: 1px solid #000")[user[1].cognome],
                     tags.td(style="border: 1px solid #000")[user[1].email],
                     tags.td(style="border: 1px solid #000")[user[0].subname],
                     tags.td(style="border: 1px solid #000")[exp],
                     tags.td(style="border: 1px solid #000")[user[1].lingua],
                     tags.td(style="border: 1px solid #000")[
                           tags.a(href="/userlist/registered/dett/"+user[1].uniqueid,
                              style="text-decoration:none; background: #99ccff")['dettaglio']
                        ],
                     ]
               res.append(ures)
            result = tags.table(style="border: 1px solid #000")[res]

            return result
      except:
         return 'Nessun risultato'
      return 'Nessun risultato'

class Registered(formal.ResourceMixin, rend.Page, Translator):

   addSlash=True
   docFactory = loaders.xmlfile('userlist_Registered.html', templateDir=template_path)

   def __init__(self, parent):
      self.parent = parent
      self.querydata  = {}
      self.formsubmitted = False
      self.childFactory = self.parent.childFactory
      self.render_HEADER = self.parent.render_HEADER
      self.render_FOOTER = self.parent.render_FOOTER
      self.render_HEAD = self.parent.render_HEAD
      self.render_Menu = self.parent.render_Menu
      formal.ResourceMixin.__init__(self)
      rend.Page.__init__(self)
      
   def render_numRegistered(self, ctx, data):
      return 'Utenti registrati: '

   def render_getForm(self, ctx, data):
      if 'postdata' in ctx.locate(inevow.IRequest).args:
         request = inevow.IRequest(ctx)
         if request.method == "GET":
            postdata = ctx.locate(inevow.IRequest).args['postdata'][-1]
            self.querydata = pickle.loads(base64.urlsafe_b64decode(postdata))
      return tags.directive("form userdbquery")


   def getResult(self, data):
      return dbutils.getUserlistResult(data)

   def render_getResults(self, ctx, data):
      if len(self.querydata) > 0:
         users = self.getResult(self.querydata)
         try:
            if len(users) > 0:
               res = [tags.tr[
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['USERNAME']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['NOME']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['COGNOME']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['EMAIL']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['ULTIMO LOGIN']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['DATA ISCRIZIONE']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b['LINGUA']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b[' ']],
                  tags.td(style="border: 1px solid #000; background-color: #CCFF00")[tags.b[' ']]
                  ]
               ]
               for user in users:
                  try:
                     llogin = user.lastlogin.asHumanly()
                  except:
                     llogin = 'Mai'
                  dellink = str(user.uniqueid)+"/"+base64.urlsafe_b64encode(pickle.dumps(self.querydata))
                  ures = tags.tr[
                        tags.td(style="border: 1px solid #000")[user.username],
                        tags.td(style="border: 1px solid #000")[user.nome],
                        tags.td(style="border: 1px solid #000")[user.cognome],
                        tags.td(style="border: 1px solid #000")[user.email],
                        tags.td(style="border: 1px solid #000")[llogin],
                        tags.td(style="border: 1px solid #000")[user.tsiscrizione.asHumanly()],
                        tags.td(style="border: 1px solid #000")[user.lingua],
                        tags.td(style="border: 1px solid #000")[
                              tags.a(href="/userlist/registered/dett/"+user.uniqueid,
                                 style="text-decoration:none; background: #99ccff")['dettaglio']
                           ],
                        tags.td(style="border: 1px solid #000")[
                           tags.a(href="/userlist/registered/userdel/"+dellink,
                                 style="text-decoration:none; background: #99ccff",
                                 onClick="return confirm('Sicuro?');")['elimina']
                           ]
                        ]
                  res.append(ures)
               result = tags.table(style="border: 1px solid #000")[res]
               return result
         except:
            return 'Nessun risultato'
         return 'Nessun risultato'
      return ' '

   def form_userdbquery(self, ctx):
      form = formal.Form()
      form.addField('nome', formal.String(strip=True, required=False), label=self.translate(ctx, 'name'))
      form.addField('cognome', formal.String(strip=True, required=False), label=self.translate(ctx, 'surname'))
      form.addField('citta', formal.String(strip=True), label=self.translate(ctx, 'city'))
      form.addField('email', formal.String(required=False, strip=True,
         validators=[formal.PatternValidator(regex=validators.REGEX_EMAIL)]),
         label=self.translate(ctx, 'email'))
      form.addField('username', formal.String(strip=True, required=False), label=self.translate(ctx, 'username'))
      form.addAction(self.submitted, label='Query')
      form.data = self.querydata
      return form


   def submitted(self, ctx, form, data):
      # XXX this is a very bad hack
      request = inevow.IRequest(ctx)
      request.method = "GET"
      
      if not self.formsubmitted:
         self.formsubmitted = True
         self.querydata = data
         return self
      else:
         self.formsubmitted = False

   def child_dett(self, ctx):
      return Dettails(self)

   def child_userdel(self, ctx):
      childctx=inevow.IRemainingSegments(ctx)
      refresh="/".join(inevow.ICurrentSegments(ctx))
      if len(childctx) == 3:
         log.debug("REMOVING USER UUID: %s" % childctx[1])
         dbutils.safeDelUser(childctx[1])
         return RefreshPost("/"+refresh, childctx[2])
      else:
         return Refresh("/"+refresh)



class ConnectedList(rend.Page):

   addSlash=True
   docFactory = loaders.xmlfile('userlist_ConnectedList.html', templateDir=template_path)


   def __init__(self, parent):
      self.parent = parent
      self.childFactory = self.parent.childFactory
      self.render_HEADER = self.parent.render_HEADER
      self.render_FOOTER = self.parent.render_FOOTER
      self.render_HEAD = self.parent.render_HEAD
      self.render_Menu = self.parent.render_Menu
      self.command = self.parent.command
      rend.Page.__init__(self)
   

   def render_Userlist(self, ctx, data):
      ulist = self.command('UserList')
      ucount = str(len(ulist))
      html = '<div id="userlist"><table style="border: 1px solid #000" border="1">'
      html = html+'<tr><td colspan="6" align="center"><b>TOTUSERS: '+ucount+'</b></td></tr>'
      html = html+'<tr><td width="5%"></td><td width="10%"><b>Username</b></td>'
      html = html+'<td width="15%"><b>Client Version</b></td>'
      html = html+'<td width="35%"><b>OS String</b></td><td><b>IP</b></td><td></td></tr>'
      ulist.sort(key=str.lower)
      c=1
      for user in ulist:
         userd = self.command('getUserData', user)
         html = html+'<tr><td>'+str(c)+'.</td>'
         html = html+'<td><b>'+user+'</b></td>'
         html = html+'<td>'+str(userd['connection'].clientversion)+'</td>'
         html = html+'<td> '+str(userd['connection'].osversion).replace("<","").replace(">", "")+'</td>'
         try:
            html = html+'<td> '+str(userd['connection'].myip[1])+'</td>'
         except:
            html = html+'<td>Unknown</td>'
         html = html+'<td><a href="/killuser/'+user+'">Disconnetti utente</a></td></tr>'
         c=c+1
      html=html+'</table></div>'
      return ctx.tag[loaders.xmlstr(html)]



class Page(rend.Page):
   
   addSlash=True
   docFactory = loaders.xmlfile('userlist.html', templateDir=template_path)

   def __init__(self, avatarId=None):
      self.avatarId = avatarId
      log.debug("Requested Userlist by "+str(avatarId))
      rend.Page.__init__(self)

   def render_Usernum(self, ctx, data):
      unum = self.command('UserNum')
      ureg = self.command('UserReg')
      return str(unum)

   def render_Userreg(self, ctx, data):
      ureg = self.command('UserReg')
      return str(ureg)

   def child_registered(self, ctx):
      return Registered(self)

   def child_subscribed(self, ctx):
      return Subscribed(self)

   def child_connected(self, ctx):
      return ConnectedList(self)

   def render_Menu(self, ctx, data):
      return Menu()


   def childFactory(self, ctx, data):
      return self.childPermissionDenied()
