from twisted.web import resource, static
from twisted.internet import defer
import cgi, logging
from nevow import inevow, rend, tags, loaders, flat
from zope.interface import implements
import os, sys
import formal
from formal import iformal
from webgui import GenericFormalResponsePage, Translator
from utils import validators, mail, pwgen, nations, timezones
from Database import utils as dbutils
import pytz

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


user_languages = [
   ('en', 'english'),
   ('it', 'italiano'),
]


ok=tags.div[
      tags.div[
         tags.span["Registrazione effettuata con successo. Controlla l'email per i dettagli."]
      ],
      tags.div[
         tags.span["Subscription done succesfully. Pleas check your email for details."]
      ]
   ]

okemailit="""

Con questi dati potrai accedere gratuitamente per un anno 
alle immagini Live dei telescopi e alla chat annessa tutte le sere.

Per poter controllare i telescopi ed effettuare le foto a 
lunga posa, ti chiediamo un contributo di 100 euro per un anno
da inviare tramite bonifico bancario o Carta di Credito con il 
metodo SICURO e veloce online PAYPAL.

Se dovessi scegliere di effettuare il contributo tramite Carta di Credito, 
basta cliccare nella home page su DONAZIONI PROGETTO
SKYLIVE e seguire le semplici istruzioni.
L'abilitazione al controllo totale del telescopi avverra' 
entro 24 ore dal versamento effettuato.

Il Telescopi Remoti N.5 e N.6 situati in Australia prevedono 
un contributo ulteriore di 50 euro annuali, opzionali. 
Con questi telescopi si possono osservare oggetti dell'Emisfero Sud, 
non visibili dall'Italia!!!

Grazie a questi contributi, miglioreremo sempre di piu' la quaita' 
delle immagini e il Sistema Skylive aggiungendo altri 
Telescopi con controllo remoto.

Rispondi a questa mail se vuoi sapere i dettagli 
e i dati per effettuare il bonifico.


Grazie,

Lo staff Skylive
http://www.skylive.it


"""


okemailen="""

With this data you are are able to see for free and for one year 
the live images of the telescopes of the skylive project. 

To be enabled to control the telescopes and make long exposure photos, 
we ask youn in change a contribute of 100 euro at year to send 
trough bank transfer or credit card using the safe and speedy method PAYPAL.

50 euro/year as option are required to use the Australian telescopes.

Send an email to us if you need information for bank transation. 
If you choose to send the money with credit card, you need just 
to click in the english home page on 'Send association fee' 
and follow the simple instructions.

Your account will be enabled to the full control of the telescopes 
within 24 hours after transation. 

Thanks to these donations we will add more instruments 
to be used remotely from alle enabled users.

Please answer to this email if you need more informations about the project.

Thanks and clear skyes,

The Skylive staff.
http://www.skylive.it/skylive-new/index.php?lan=en

"""

no=tags.div[
      tags.span["Sorry, ther's an error on the server. Please contact info@skylive.it!"]
   ]


def makeoption(opt):
   return (str(opt), str(opt))


class FormLink(object):
   implements( iformal.IWidget )

   def __init__(self, original, translator=False, ctx='web'):
      self.original = original
      self.translate = translator
      self.ctx = ctx
      print self.translate

   def render(self, ctx, key, args, errors):
      t=tags.a(href=self.translate(ctx, 'toulink'),
       target="blank")[self.translate(ctx, 'termsofusage')]
      return t

   def renderImmutable(self, ctx, key, args, errors):
      return self.render(self, ctx, key, args, errors)

   def processInput(self, ctx, key, args):
      return True

class RegisteredPage(GenericFormalResponsePage):

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

   def render_nome(self, context, data):
      pwd = pwgen.GeneratePwd()
      if dbutils.newUser(self.data, pwd):
         m = mail.TextEmail()
         m.SetTo(self.data['email'])
         m.SetFrom("robot@skylive.it")
         m.SetCc("info@skylive.it")
         m.SetReply("info@skylive.it")
         if str(self.data['language']) == 'it':
            m.SetSubject("Benvenuto in SkyLive!")
            strmsg="Registrazione a skylive effettuata con successo!\n\n"
            strmsg+="Il tuo nome utente e': "+str(self.data['username'])+"\n"
            strmsg+="La tua password e': "+str(pwd)
            strmsg+="\n\n"
            strmsg+=okemailit
         else:
            m.SetSubject("Welcome to SkyLive!")
            strmsg="Registration to skylive done with success!\n\n"
            strmsg+="Your username is: "+str(self.data['username'])+"\n"
            strmsg+="Your password is: "+str(pwd)
            strmsg+="\n\n"
            strmsg+=okemailen
         m.SetMsg(strmsg)
         m.Send()  
         return ok
      else:
         return no



class Page(formal.ResourceMixin, rend.Page, Translator):
   
   addSlash=True
   docFactory = loaders.xmlfile('registration.html', templateDir=template_path)

   def __init__(self, avatarId=None):
      self.avatarId = avatarId
      log.debug("Requested Registration "+str(avatarId))
      self.formsubmitted = False
      rend.Page.__init__(self)


   def render_getForm(self, context, data):
      return tags.directive("form registration")


   def form_registration(self, ctx):
      form = formal.Form()
      form.addField('language', formal.String(strip=True, required=True),
                        formal.widgetFactory(formal.SelectChoice, options=user_languages,
                                          noneOption=None), label=self.translate(ctx, 'language'))


      form.addField('name', formal.String(strip=True, required=True), label=self.translate(ctx, 'name'))
      form.addField('surname', formal.String(strip=True, required=True), label=self.translate(ctx, 'surname'))
      form.addField('city', formal.String(strip=True, required=True), label=self.translate(ctx, 'city'))

      form.addField('nation', formal.String(strip=True, required=True),
                        formal.widgetFactory(formal.SelectChoice, options=nations.nations,
                                          noneOption=None), label=self.translate(ctx, 'nation'))

      form.addField('tzone', formal.String(strip=True, required=True),
                        formal.widgetFactory(formal.SelectChoice, options=timezones.worldtz,
                                          noneOption=None), label=self.translate(ctx, 'tzone'))


      form.addField('email', formal.String(required=True, strip=True,
         validators=[formal.PatternValidator(regex=validators.REGEX_EMAIL), validators.EmailExistsValidator()]), 
         label=self.translate(ctx, 'email'))
      form.addField('username', formal.String(strip=True, required=True,
         validators=[validators.UsernameExistsValidator(), validators.ValidUsername()]), label=self.translate(ctx, 'username'))
      form.addField('prefobj', formal.String(strip=True, required=True),
                        formal.widgetFactory(formal.SelectChoice, options=self.translate(ctx, 'prefobjchoice'),
                                          noneOption=None), label=self.translate(ctx, 'prefobj'))


      form.addField("link", formal.String(strip=False, validators=[]) , formal.widgetFactory(FormLink, 
         translator=self.translate, ctx=ctx), label='')

      form.addField('mlist', formal.String(strip=True),
            formal.widgetFactory(formal.RadioChoice, options=[('yes', self.translate(ctx, 'yes')),
               ('no', self.translate(ctx, 'no'))]),
            label=self.translate(ctx, 'mlist_subscribe'))


      form.addField('policy', formal.String(strip=True,
         validators=[validators.AcceptPolicy(errmsg='You MUST accept our terms of usage to register!')]), 
            formal.widgetFactory(formal.RadioChoice, options=[('yes', self.translate(ctx, 'yes')),
               ('no', self.translate(ctx, 'no'))]),
            label=self.translate(ctx, 'registration_policy'))
      form.addAction(self.submitted, label='Send')
      l = 'it'
      if 'lang' in ctx.locate(inevow.IRequest).args:
         l= ctx.locate(inevow.IRequest).args['lang'][-1]
      form.data = {
            'policy': 'no',
            'mlist': 'yes',
            'language': l,
            'nation': "Italy",
            'tzone': 'Europe/Rome',
            }
      return form


   def submitted(self, context, form, data):
      self.formsubmitted = True
      print form, data
      return RegisteredPage(data, self)
      #return error_pattern or context.tag().clear()


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