from pyramid.view import (
        forbidden_view_config,
        view_config,
)

from pyramid.httpexceptions import HTTPFound
from pyramid.security import remember, forget
from pyramid_mailer.message import Message, Attachment

from ..models.users import *
from ..models.entries import *
from datetime import datetime
from urllib import request, parse
from passlib.apps import custom_app_context as blogger_pwd_context

import os
import shutil
import magic
import json
import pkg_resources
import sys
import sqlite3
import transaction


@view_config(route_name='home', renderer='../templates/home.jinja2')
def home(request):
 
    return {
        'page_title': "",
        }

def captcha_validate(response, remote_addr, secret):
    VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'  
    data = {
        'secret': secret,
        'response': response,
        'remoteip': remote_addr,
    }

    encoded = parse.urlencode(data).encode()

    req = request.Request(VERIFY_URL, data=encoded)

    with request.urlopen(req) as resp:
        json_resp = json.loads(resp.read().decode('utf-8'))

        if json_resp['success']:
            return (True, None)
        else:
            return (False, json_resp['error-codes'])


@view_config(route_name='settings', renderer='../templates/settings.jinja2', permission='view')
def settings(request):

    # lire toutes les docs du topic
    topic = '_admin'
    items = get_last_edited(request)

    # informations sur les versions
    pyramid_version = pkg_resources.get_distribution("pyramid").version
    markdown_version = pkg_resources.get_distribution("markdown").version
    sqlalchemy_version = pkg_resources.get_distribution("sqlalchemy").version
    sqlite_version = sqlite3.sqlite_version
    python_version = sys.version
    # app_version = pkg_resources.require("tcs_site")[0].version

    return {
        'page_title': "Paramètres",
        'topic': topic,
        'items': items,
        'pyramid_version': pyramid_version,
        'markdown_version': markdown_version,
        'sqlite_version' : sqlite_version,
        'sqlalchemy_version': sqlalchemy_version,
        'python_version' : python_version,
        }


@view_config(route_name='login', renderer='../templates/login.jinja2')
@forbidden_view_config(renderer='../templates/login.jinja2')
def login(request):
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/' # never use the login form itself as came_from

    came_from = request.params.get('came_from', referrer)
    username = ''
    userpwd = ''
    if 'form.submitted' in request.params:
        username = request.POST.get('username')
        userpwd = request.POST.get('password')
        user = get_users_by_name(request, username)
        # Is user existed ?
        if user :
            # is it cleartext?
            if userpwd == user.password:
                password_hash = blogger_pwd_context.encrypt(user.password)
            else:
                password_hash = user.password

            if blogger_pwd_context.verify(userpwd, password_hash):
                # pwd OK, set last login date
                update_last_connection(request, user.id, password_hash)
                # force le commit car il ne se fait pas automatiquement après l'update
                transaction.commit()
                headers = remember(request, username)
                request.session.flash("Bienvenue %s !" % username, 'success')
                return HTTPFound(location=came_from, headers=headers)
        # pwd NOK, error message
        headers = forget(request)
        request.session.flash("Login et mot de passe invalides. La connexion a échoué.", "danger")

    return {
        'page_title': "",
        'came_from': came_from,
        'login_url': login_url,
        }

@view_config(route_name='contact', renderer='../templates/contact.jinja2')
def contact(request):
    name = ''
    email = ''
    comments = ''
    
    # import pdb;pdb.set_trace()

    if 'form.submitted' in request.params : 
        name = request.params['name']
        email = request.params['email']
        comments = request.params['comments']
        response = request.params['response']

        # verification reCaptcha ?
        ok, erreur = captcha_validate(response, request.remote_addr, request.registry.settings['secret_key'])
        if ok and comments != '':
            # no, message is not spam, send it
            body = """
<p>Bonjour,</p>
<p>L'expéditeur <b>{0}</b> ( {1} ), a envoyé le message suivant via le site web : </p>
<p>-----  Début du message -----</p>
<p><b>
{2}
</b></p>
<p>-----  Fin du message -----</p>
<P>Cordialement,</p>
<p>webmaster@meditation-sunyata.paris</p>
""".format(name, email, comments)

            body_html = Attachment(data=body, transfer_encoding="base64", disposition='inline')
            message = Message(subject="[MSParis] Message du site web",
                            sender=request.registry.settings['admin_email'],
                            html=body_html)
            message.add_recipient(request.registry.settings['admin_email'])
            mailer = request.registry['mailer']
            mailer.send_immediately(message)
            request.session.flash("Votre message a bien été envoyé au webmestre. Merci de votre intérêt pour notre site.", "success")
            return HTTPFound(location=request.route_url('home'))

    return {
        'page_title': "Contact - Liên hệ",
        'name': name,
        'email': email,
        'comments': comments,
        'site_key' : request.registry.settings['site_key'],
        }



@view_config(route_name='logout', renderer='string')
def logout(request):
    username = request.authenticated_userid
    if username == None:
        username = ''
    
    headers = forget(request)
    request.session.flash('Au revoir ' + username + ' !', 'success')
    return HTTPFound(location=request.route_url('home'), headers=headers)

@view_config(route_name='users', renderer='../templates/users.jinja2', permission='manage')
def users(request):
    # get all users
    users = get_users_all(request)
    return {
        'page_title': "Liste des utilisateurs",
        'users': users
        }


@view_config(route_name='user_edit', renderer='../templates/user_edit.jinja2', permission='view')
def user_edit(request):
    name = request.matchdict['name']
    url = request.route_url('user_edit', name=name)
    if request.authenticated_userid == 'admin':
        url_retour = request.route_url('users')
    else:
        url_retour = request.route_url('home')

    if name == '0':
        # nouvel utilisateur
        user = {}
        user['id'] = 0
        user['name'] = ''
        user['password'] = ''
        user['last_logged'] = None
        page_title = "Nouvel utilisateur"
    else:
        # lire la fiche du user 
        user = get_users_by_name(request, name)
        if not user:
            request.session.flash("Utilisateur non trouvé : %s" % name, 'danger')
            return HTTPFound(location=url_retour)

        page_title = "Modification utilisateur"

    if 'form.submitted' in request.params:
        new_values = {}
        for param in user.keys():
            if param in request.params and request.params[param] != user[param]:
                new_values[param] = request.params[param]
                
        if new_values:            
            update_user(request, name, new_values)
            request.session.flash(u"La fiche a été mise à jour avec succès.", 'success')
            return HTTPFound(location=url_retour)

    
    if 'form.deleted' in request.params:
        delete_user(request, user.id)
        request.session.flash("La fiche a été supprimée avec succès.", 'success')
        return HTTPFound(location=url_retour)

    return {
        'page_title': page_title,
        'url': url,
        'url_retour': url_retour,
        'name': name,
        'user': user,
        }


@view_config(route_name='topics', renderer='../templates/topics.jinja2', permission='view')
def topics(request):
    # get all topics
    topics = get_topics(request)
    return {
        'page_title': "Liste des Topics",
        'topics': topics
        }

@view_config(route_name='topic_edit', renderer='../templates/topic_edit.jinja2', permission='view')
def topic_edit(request):
    # get topic parameters from request
    topic = request.matchdict['topic'] 
    url = request.route_url('topic_edit',topic=topic)

    # get the list of tags of this topic
    tags = get_tags_byTopic(request, topic)

    if topic == '0':
        # create a new topic
        entry = {}
        entry['topic'] = ''
        entry['topic_name'] = ''
        entry['topic_language'] = ''
        entry['topic_quote'] = ''
        page_title = "Nouveau topic"
    else:
        # modify post
        entry = get_topic_byTopic(request, topic)
        if not entry:
            request.session.flash(u"Topic non trouvé : %s" % topic, 'warning')
            return HTTPFound(location=request.route_url('topics'))
        page_title = entry.topic_name

    if 'form.submitted' in request.params:
        new_values = {}
        for param in entry.keys():
            if param in request.params and request.params[param] != entry[param]:
                new_values[param] = request.params[param]
                
        # import pdb;pdb.set_trace()
        if new_values:            
            update_topic(request, topic, new_values)
            request.session.flash(u"La fiche a été mise à jour avec succès.", 'success')
            return HTTPFound(location=request.route_url('topics'))
           
    if 'form.deleted' in request.params:
        delete_topic(request, entry.topic)
        request.session.flash("La fiche a été supprimée avec succès.", 'success')
        return HTTPFound(location=request.route_url('topics'))

    return {
        'page_title': page_title,
        'url': url,
        'entry': entry,
        'tags': tags,
        }

@view_config(route_name='tag_edit', renderer='../templates/tag_edit.jinja2', permission='view')
def tag_edit(request):
    # get tag parameters from request
    topic = request.matchdict['topic'] 
    tag_id = request.matchdict['id'] 
    url = request.route_url('tag_edit', topic=topic, id=tag_id)

    if tag_id == '0':
        # create a new tag
        entry = {}
        entry['topic'] = ''
        entry['tag'] = ''
        entry['tag_name'] = ''
        page_title = "Nouveau Tag"
    else:
        # modify post
        entry = get_tags_byId(request, tag_id)
        if not entry:
            request.session.flash(u"Tag non trouvé : %s" % tag_id, 'warning')
            return HTTPFound(location=request.route_url('topic_edit', topic=topic))
        page_title = entry.tag_name

    if 'form.submitted' in request.params :
        new_values = {}
        for param in entry.keys():
            if param in request.params and request.params[param] != entry[param]:
                new_values[param] = request.params[param]
                
        # import pdb;pdb.set_trace()
        if new_values:
            new_values['topic'] = topic            
            update_tag(request, tag_id, new_values)
            request.session.flash(u"La fiche a été mise à jour avec succès.", 'success')
            return HTTPFound(location=request.route_url('topic_edit', topic=topic))

    if 'form.deleted' in request.params:
        delete_tag(request, tag_id)
        request.session.flash("La fiche a été supprimée avec succès.", 'success')
        return HTTPFound(location=request.route_url('topic_edit', topic=topic))

    return {
        'page_title': page_title,
        'url': url,
        'entry': entry,
        'topic': topic,
        }


