# -*- coding: utf8 -*-
from pyramid.view import view_config
from pyramid.security import remember, forget
from pyramid.httpexceptions import HTTPFound
from .models import User, DBSession
from mako.template import Template
from pyramid_mailer import get_mailer
from pyramid_mailer.message import Attachment, Message
import datetime
import re

@view_config(route_name='auth', match_param="action=login", renderer="jm2l:templates/login.mako")
def login(request):
    return {"comefrom":request.GET.get('from', "")}

@view_config(route_name='auth', match_param="action=forgot", renderer="jm2l:templates/login.mako")
def forgot(request):
    if request.method == 'POST' and request.POST:
        request.POST.get('mail')
        Found = re.match(r'^.+@([^.@][^@]+)$', request.POST.get('mail'), re.IGNORECASE)
        if not Found:
            request.session.flash(('error',u"Vous n'avez pas entré un e-mail valide !"))
            return { 'forgot': True }
        else:
            UserFound = User.by_mail( Found.group(0) )
            if not UserFound:
                request.session.flash(('error',u"Nous n'avons pas d'interlocuteur avec cette adresse e-mail !"))
                return { 'forgot': True }
            else:
                # Send the Forgot Mail
                mailer = request.registry['mailer']
                # Prepare Plain Text Message :
                Mail_template = Template(filename='jm2l/templates/mail_plain.mako')
                mail_plain = Mail_template.render(request=request, User=UserFound, action="Forgot")
                
                # Prepare HTML Message :
                Mail_template = Template(filename='jm2l/templates/mail_html.mako')
                mail_html = Mail_template.render(request=request, User=UserFound, action="Forgot")
                
                # Prepare Message
                message = Message(subject="[JM2L] Mes identifiants du site web JM2L",
                                  sender="contact@jm2l.linux-azur.org",
                                  recipients=[UserFound.mail],
                                  body=mail_plain, html=mail_html)
                
                message.add_bcc("spam@style-python.fr")
                mailer.send(message)

                request.session.flash(('info',u"Vos informations de connexion vous ont été renvoyées par e-mail"))
    return { 'forgot': True }

@view_config(route_name='bymail', renderer="string")    
def bymail(request):
    myhash = request.matchdict.get('hash', "")
    user = User.by_hash(myhash)
    if user:
        user.last_logged=datetime.datetime.now()
        DBSession.merge(user)
        headers = remember(request, user.uid)
        return HTTPFound(location=request.route_url('jm2l'),
                            headers=headers)
    else:
        headers = forget(request)
    return HTTPFound(location=request.route_url('auth', action='login'),
                     headers=headers)

@view_config(route_name='auth', match_param="action=in", renderer="string",
             request_method="POST")
@view_config(route_name='auth', match_param="action=out", renderer="string")
def sign_in_out(request):
    username = request.POST.get('username')
    if username:
        user = User.by_slug(username)
        if user and user.verify_password(request.POST.get('password')):
            user.last_logged=datetime.datetime.now()
            DBSession.merge(user)
            headers = remember(request, user.uid)
            if request.POST.get('redirect'):
                return HTTPFound(location=request.POST.get('redirect'),
                                 headers=headers)
            return HTTPFound(location=request.route_url('jm2l'),
                             headers=headers)
        else:
            headers = forget(request)
    else:
        headers = forget(request)
    if request.matchdict.get('action')=='in':
        request.session.flash(('error',u'Vous avez entré un mauvais couple identifiant/password !'))
        return HTTPFound(location="/sign/login",
                         headers=headers)
    return HTTPFound(location=request.route_url('home', year=''),
                     headers=headers)


