from twisted.web import resource, static
import cgi, logging
from nevow import inevow, rend, tags, loaders, flat

import os, sys


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

emailDiscl = """
--
Hai ricevuto questo messaggio dal gruppo Skylive in quanto sei un
Utente iscritto al Progetto Skylive.
L'indirizzo del sito e' http://www.skylive.it.
Se non desideri piu' ricevere informazioni da questa mailing list,
rispondi scrivendo come soggetto 'cancella'
--------------------------------------------------------
You are receiving this message from the skylive staff
cause you are subscribed to the skylive project.
Our web site address is http://www.skylive.it.
If you don't want to receive infos from this mailing list,
please reply to this email with "remove"  as subject of the email
--------------------------------------------------------
"""

emailDisclHTML = """
<br />
--<br />
Hai ricevuto questo messaggio dal gruppo Skylive in quanto sei un <br />
Utente iscritto al Progetto Skylive.<br />
L'indirizzo del sito e' http://www.skylive.it.<br />
Se non desideri piu' ricevere informazioni da questa mailing list,<br />
rispondi scrivendo come soggetto 'cancella'<br />
--------------------------------------------------------<br />
You are receiving this message from the skylive staff<br />
cause you are subscribed to the skylive project.<br />
Our web site address is http://www.skylive.it.<br />
If you don't want to receive infos from this mailing list,<br />
please reply to this email with "remove"  as subject of the email<br />
--------------------------------------------------------<br />
<br />

"""


def sort_list(seq, idfun=None):
   if idfun is None:
      def idfun(x): return x
   seen = {}
   res = []
   for item in seq:
      marker = idfun(item)
      if marker in seen: continue
      seen[marker] = 1
      res.append(marker)
   return res

class Menu(rend.Fragment):

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


class Status(rend.Page):

   addSlash=True
   docFactory = loaders.xmlfile('rapidfunc_Status.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
      rend.Page.__init__(self)

   

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

   
   def __init__(self, parent, conttxt=False, conthtml=False):
      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
      self.conttxt = conttxt
      self.conthtml = conthtml
      self.error = False
      rend.Page.__init__(self)

   def render_getFormAction(self,ctx, data):
      return '/rapidfunc/Email'


   def render_getMailDef(self, ctx, data):
      if self.conttxt:
         return conttxt
      else:
         return emailDiscl

   def render_getError(self, ctx, data):
      if self.error:
         err = self.error
         self.error = False
         return err
      else:
         return ' '
 

   def render_getMailDefHTML(self, ctx, data):
      if self.conthtml:
         return self.conthtml
      else:
         return emailDisclHTML

   def render_getCities(self, ctx, data):
      citylist = self.command("citiesList")
      html="<select name=\"city\">"
      html+="<option value=\"all\">TUTTE</option>"
      cities = sort_list(citylist, lambda x: " ".join(x.split()).encode('ascii', 'xmlcharrefreplace').capitalize())
      cities.sort()
      for i in cities:
         cn = unicode(i).encode('ascii', 'xmlcharrefreplace').replace("\"", "\\\"")
         html+="<option value=\""+cn+"\">"+cn+"</option>"
      html+="</select>\n"
      return ctx.tag[loaders.htmlstr(html)]


   def renderHTTP(self, ctx):
      log.debug("Called renderHTTP")
      request = inevow.IRequest(ctx)
      if request.method == 'POST':
         log.debug("POST RapidFunc/Email")
         try:
         #if True:
            if request.args["InviaMsg"][0] == 'Invia Messaggio':
               log.debug("Requested Send Email")
               msg=request.args["msg"][0]
               msghtml=request.args["msghtml"][0]
               mtype=request.args["mtype"][0]
               dest=request.args["dest"][0]
               city=request.args["city"][0]
               language=request.args["lang"][0]
               subject=request.args["subject"][0]
               #dest=request.args["recp"][0]
               ulist=request.args["ulist"][0]
               rmlist=request.args["mlist"][0]
               if rmlist=='yes':
                  mlist=True
               else:
                  mlist=False
               self.error = 'Email correctly sent'
               self.command("EmailMessage", msg, msghtml, mtype, subject, dest, language, ulist, city, mlist)
         except:
            self.conttxt = msg
	    self.conthtml = msghtml
            self.error = 'Email not sent!'
      return rend.Page.renderHTTP(self, ctx)



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

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


   def renderHTTP(self, ctx):
      log.debug("Called renderHTTP")
      request = inevow.IRequest(ctx)
      if request.method == 'POST':
         log.debug("POST RapidFunc")
         try:
            if request.args["InviaMsg"][0] == 'Invia Messaggio':
               log.debug("Requested Global Message")
               msg=request.args["msg"][0]
               mitt=request.args["mitt"][0]
               tipo=request.args["type"][0]
               w=request.args["width"][0]
               h=request.args["heigth"][0]
               if int(w) < 200 or int(w) > 1600:
                  w="530"
               if int(h) < 150 or int(h) > 1200:
                  h="310"
               dest=request.args["recp"][0]
               if dest=="users":
                  dest=request.args["ulist"][0]
                  gmsg=False
               else:
                  gmsg=True
               log.debug("Requested Message from "+str(mitt)+", type "+tipo+", text: "+str(msg))
               self.command("GlobalMessage", tipo, mitt, msg, dest, w, h, gmsg)
         except:
            pass
      return rend.Page.renderHTTP(self, ctx)

   def render_getFormAction(self,ctx, data):
      return '/rapidfunc'

   def order_tlist(self, tlist):
      res = {}
      for i in tlist.keys():
         res[tlist[i]['name']] = tlist[i]
         res[tlist[i]['name']]['index'] = i
      return res


   def render_selectTelescope(self, ctx, data):
      self.tlist = self.order_tlist(self.command('GetTelescopes'))
      keys = self.tlist.keys()
      keys.sort()
      html="<select name=\"recp\">"
      html+="<option value=\"all\">TUTTI</option>"
      html+="<option value=\"users\">LISTA UTENTI</option>"
      for i in keys:
         html+="<option value=\""+str(self.tlist[i]['index'])+"\">"+self.tlist[i]['name']+"</option>"
      html+="</select>"
      return ctx.tag[loaders.xmlstr(html)]

   def child_Status(self, ctx):
      return Status(self)

   def child_Email(self, ctx):
      return Email(self)


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

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