from adrianremembersme import *

import os
from google.appengine.ext.webapp import template
import cgi
import wsgiref.handlers
from google.appengine.ext.webapp.util import run_wsgi_app
import urllib
from google.appengine.api import urlfetch
from google.appengine.api import images
from google.appengine.api import mail
from google.appengine.ext import db
from google.appengine.ext import webapp
from django.utils import simplejson
import random
import pprint
import string
from django1fields import email_re
from string import strip
import re

LANG_EN = {
    "name":"Name",
    "photo":"Photo",
    "update":"Update",
    "people":"People",
    "password":"Password",
    "email":"Email Address",
}
LANG_ES = {
    "name":"Nombre",
    "photo":"Foto",
    "update":"Actualizar",
    "people":"Personas",
    "password":"Contraseña",
    "email":"Dirección de correo electrónico",
}
LANG = LANG_EN

class MainPage(webapp.RequestHandler):
    def get(self):
        template_values = {
            'lang': LANG
            }  
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class MemberEdit(webapp.RequestHandler):
    def get(self):
        name = urllib.unquote(self.request.cookies.get('ack', ''))
        template_values = {
            'name': name,
            'lang': LANG
            }
        path = os.path.join(os.path.dirname(__file__), 'member.html')
        self.response.out.write(template.render(path, template_values))
        
    def post(self):
        # look for existing user, if doesn't exist create one, set cookie
        arm = AdrianRemembersMe()
        
        errcode = arm.ERROR_OK
        errmsg = ""
        tname = strip(self.request.get('name'))
        temail = strip(self.request.get('email'))
        tpassword = self.request.get('password')

        if arm.emailisavailable(temail):
            if (self.request.POST.get('file') != "" and self.request.POST.get('file').filename):
                filedata = self.request.POST.get('file').file.read()
                filename = self.request.POST.get('file').filename
                errcode = arm.membercreate(tname, tpassword, temail, filedata, filename)
            else:
                errcode = arm.membercreate(tname, tpassword, temail)
            
            if errcode == arm.ERROR_OK:
                cookie = arm.memberlogin(tname, tpassword)
                
                if cookie:
                    self.response.headers.add_header('Set-Cookie', 'ack=%s; expires=Fri, 31-Dec-2030 23:59:59 GMT' % urllib.quote(cookie))
            elif errcode == arm.ERROR_EMAIL_BAD:
                errmsg = "bad email"    
            elif errcode == arm.ERROR_EMAIL_USED:
                errmsg = "sorry, email already in use for another account"
            elif errcode == arm.ERROR_PASSWORD_WEAK:
                errmgs = "password not long enough"
            elif errcode == arm.ERROR_USERNAME_NONE:
                errmsg = "missing username"
            elif errcode == arm.ERROR_USERNAME_TAKEN:
                errmsg = "username already taken, please try another"
        else:
            errmsg = "sorry, email already in use for another account"
        
        template_values = {
            'lang': LANG,
            'errmsg': errmsg,
            'nameencoded': tname,
            }
        
        path = os.path.join(os.path.dirname(__file__), 'memberprocess.html')
        self.response.out.write(template.render(path, template_values))
        
class Login(webapp.RequestHandler):
    def get(self):
        oldurl = self.request.get("oldurl")
        if oldurl == "":
            oldurl = "/"
        
        template_values = {
            'lang': LANG,
            'oldurl': oldurl            
            }
        
        if self.request.get("error"):
            template_values["errormsg"] = "Bad e-mail/password combination"
        
        path = os.path.join(os.path.dirname(__file__), 'login.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        # check if pwd ok, look up user by username
        arm = AdrianRemembersMe()
        error = True
        membername = self.request.get('name')
        password = self.request.get('password')
            
        oldurl = self.request.get("oldurl")
        if oldurl == "":
            oldurl = "/"
                        
        cookie = arm.memberlogin(membername, password)
        if cookie:
            self.response.headers.add_header('Set-Cookie', 'ack=%s; expires=Fri, 31-Dec-2030 23:59:59 GMT' % urllib.quote(cookie))
            error = False
            
        if error:
            self.redirect("/login?" + urllib.urlencode({"oldurl":oldurl, "error":error}, False))
        else:
            self.redirect(oldurl)

class Logout(webapp.RequestHandler):
    def get(self):
        # todo: function to deliver cookieval
        arm = AdrianRemembersMe()
        cookieval = urllib.unquote(self.request.cookies.get('ack', ''))
        #empty cookie
        # todo: parametrize expiry date et al?
        self.response.headers.add_header('Set-Cookie', 'ack=; expires=Fri, 31-Dec-2030 23:59:59 GMT')
        #empty login from db
        arm.logincookieclear(cookieval)
        
class MemberList(webapp.RequestHandler):
    def get(self):
        arm = AdrianRemembersMe()
        members = arm.membergetlist()
        
        for mem in members:
            self.response.out.write(mem.name)
            memphoto = mem.photo_set.get()
            if memphoto:
                self.response.out.write(" has photo! <img src=/image?member=" + mem.name + ">")
                if memphoto.thumb:
                    self.response.out.write(" has thumbnail! <img src=/image?size=thumb&member=" + mem.name + ">")

            self.response.out.write("<p>");

class GetImage(webapp.RequestHandler):
    def get(self):
        arm = AdrianRemembersMe()
        membername = self.request.get('member')
        mem = arm.memberget(membername)
        
        #Is this meant to be for single image or multiimage?
        if mem:
            for memphoto in mem.photo_set:
                self.response.headers['Content-Type'] = 'image/jpeg'
                if self.request.get('size') == 'thumb':
                    self.response.headers['Content-Type'] = 'image/png'
                    self.response.out.write(memphoto.thumb)
                else:
                    self.response.headers['Content-Type'] = 'image/jpeg'
                    self.response.out.write(memphoto.content)


class LoginTest(webapp.RequestHandler):
    def get(self):
        arm = AdrianRemembersMe()
        member = arm.membergetloggedin(urllib.unquote(self.request.cookies.get('ack', '')))
        
        if (member):
            self.response.out.write('Hello, ' + member.name)
        else:
            self.response.out.write('Hello, -- no member ' + self.request.cookies.get('ack', ''))

class LoginList(webapp.RequestHandler):
    def get(self):
        arm = AdrianRemembersMe()
        logins = arm.logingetlist(50)
        
        for login in logins:
            self.response.out.write(login.code + "<p>\n")

class ChangePassword(webapp.RequestHandler):
    def get(self):
        # present form
        template_values = {
            'lang': LANG
            }
        path = os.path.join(os.path.dirname(__file__), 'changepassword.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        # look up user;
        arm = AdrianRemembersMe()
        cookieval = urllib.unquote(self.request.cookies.get('ack', ''))
        member = arm.membergetloggedin(cookieval)
        
        message = ""
        if member and member.password == self.request.get('oldpassword') :
            if self.request.get('newpassword') == self.request.get('newpasswordconfirm'):
                arm.loginclearmember(member, cookieval)
                newpassword = self.request.get('newpassword')
                error = arm.memberchangepassword(member, newpassword)
                
                if error == arm.ERROR_OK:
                    message = "password changed"
                    
                    if member.email:
                        mail.send_mail(sender="google@adrianscott.com",
                                       to=member.email,
                                       subject="Password Changed",
                                       body="""
                                       If this was not approved by you, now would be a good time to panic.
                                       """)
                        
            else:
                message = "new password wasn't typed in right, please go back and fix."
        else:
            message = "old password wasn't right."
 
        template_values = {
            'message': message,
            'lang': LANG
            }
        path = os.path.join(os.path.dirname(__file__), 'changepasswordprocess.html')
        self.response.out.write(template.render(path, template_values))    

class EmailValidator(webapp.RequestHandler):
  def get(self):
      for address in addresses:
        self.response.out.write("%s : %s<br>" % (repr(address), email_address.match(address)))
        if email_address.match(address):
            self.response.out.write("match<p>")
        else:
            self.response.out.write("nada<p>")
        self.response.out.write("2: %s : %s<br>" % (repr(address), email_re.match(address)))
        if email_re.match(address):
            self.response.out.write("match<p>")
        else:
            self.response.out.write("nada<p>")
            
application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/member', MemberEdit),
                                        ('/memberlist', MemberList),
                                        ('/image', GetImage),
                                        ('/login', Login),
                                        ('/logout', Logout),
                                        ('/logintest', LoginTest),
                                        ('/changepassword', ChangePassword),
                                        #('/emailvalidator', EmailValidator),
                                        #('/loginlist', LoginList)
                                        ],
                                       debug=True)     
def main():
  run_wsgi_app(application)
  
if __name__ == "__main__":
  main()
