from flask import Blueprint, Flask, request, flash, render_template, url_for, session, redirect, abort, make_response, send_file, escape
from flask_bcrypt import Bcrypt
import sqlite3
import glob, os, sys, time
from tools.utils import email_disp, valid_token_register
from socket import gethostname

app = Flask( 'pywallter' )
app.config.from_pyfile('config.py')
bcrypt = Bcrypt(app)

#### Variables ##################################################################################


DOSSIER_PERSO= app.config['DOSSIER_APP']
extensionimg = app.config['EXT_IMG']
DATABASE = app.config['DATABASE']
MAIL_SERVER = app.config['MAIL_SERVER']
XMMP_SERVER = app.config['XMPP_SERVER']
SETUID = app.config['SETUID']
BASE_URL = app.config['BASE_URL']

#################################################################################################



inscription = Blueprint('inscription', __name__, template_folder='templates')

@inscription.route( '/inscription/<token>', methods=['GET','POST'] )
def signin(token) :
    hostname = gethostname()
    url_inscription = BASE_URL+'inscription/'+token
    resp = None
    if app.config['SIGNIN_ENABLE'] and valid_token_register(token):
        if 'username' in session :
            resp = redirect(url_for('profil.profile', _external=True))
        else :
            if request.method == 'POST':
                if not(request.form['user']) or not(request.form['passwd']) or not(request.form['mail']):
                    flash(u'Il faut remplir le formulaire en entier, les champs ne peuvent pas etre vide ', 'error')
                    return render_template('inscription.html',
                                           signin_enable=app.config['SIGNIN_ENABLE'],
                                           token=token, hostname=hostname,
                                           url_inscription=url_inscription,
                                           MAIL_SERVER=MAIL_SERVER)

                user = request.form['user']
                passwd = request.form['passwd']
                mail = ""
                passwdconfirm = request.form['passwdconfirm']
                bcrypt_passwd = bcrypt.generate_password_hash(request.form['passwd'])
                mail_passwd_change = 0

                conn = sqlite3.connect(DATABASE) # Connexion à la base de donnée
                cursor = conn.cursor() # Création de l'objet "curseur"

                cursor.execute("""SELECT name FROM users WHERE name=?""", (user,))
                testuser = cursor.fetchone()
                conn.close()


                if MAIL_SERVER:
                    mail = request.form['mail'].lower()+'@'+hostname
                    if not(email_disp(mail)) :
                        flash(u'Adresse email déjà utilisé ou invalide, merci d\'en choisir une autre', 'error')
                        resp = render_template('inscription.html',
                                               signin_enable=app.config['SIGNIN_ENABLE'],
                                               token=token, hostname=hostname,
                                               url_inscription=url_inscription,
                                               MAIL_SERVER=MAIL_SERVER)
                    else:
                        cmd = SETUID + " set_mail_passwd " + "'"+mail+"' " + "'"+passwd+"'"
                        mail_passwd_change = os.system(cmd)


                if testuser or mail_passwd_change != 0 or resp:
                    flash(u'Non d\'utilisateur déjà utilisé, merci d\'en choisir un autre', 'error')
                    resp = render_template('inscription.html',
                                           signin_enable=app.config['SIGNIN_ENABLE'],
                                           token=token, hostname=hostname,
                                           url_inscription=url_inscription,
                                           MAIL_SERVER=MAIL_SERVER)

                else:
                    confirmation = bcrypt.check_password_hash(bcrypt_passwd, passwdconfirm)
                    if confirmation is True:
                        conn = sqlite3.connect(DATABASE) # Connexion à la base de donnée
                        cursor = conn.cursor() # Création de l'objet "curseur"
                        cursor.execute("""INSERT INTO users(name, mail, passwd) VALUES(?, ?, ?)""", (user, mail, bcrypt_passwd)) # Insérer des valeurs
                        conn.commit() # Sauvegarder valeurs dans la bdd


                        if XMMP_SERVER:
                            tmp = mail.split('@')
                            cmd = SETUID+ ' prosodyctl register ' "'"+tmp[0]+"' " + "'"+tmp[1]+"' " + "'"+passwd+"'"
                            res = os.system(cmd)
                            if res != 0:
                                flash(u'Il y a eu un problème pour la création du compte XMPP !', 'error')

                        cursor.execute("""SELECT name, mail, passwd FROM users""")

                        users = cursor.fetchall()
                        for i in users:
                            i = print('{0} - {1} - {2}'.format(i[0], i[1], i[2]))

                        userracine = DOSSIER_PERSO + user
                        userfiles = userracine + '/files'
                        userimages = userracine + '/images'
                        userthumbnails = userracine + '/images/thumbnails'
                        userprofile = userracine + '/profile'
                        userlog = userracine + '/log.txt'
                        if not os.path.exists(userracine):
                            os.makedirs(userracine)
                            os.makedirs(userfiles)
                            os.makedirs(userimages)
                            os.makedirs(userthumbnails)
                            os.makedirs(userprofile)
                            fp = open(userlog, 'x')
                            fp.close()


                        # Une fois que tout c'est bien passé pour l'inscription on détruit le jeton.
                        cursor.execute("""SELECT name, invitations FROM users where Token=?""", (token,))
                        tmp = cursor.fetchone()
                        username = tmp[0]
                        invitations_count=tmp[1] - 1
                        if username == "pywallter":
                            cursor.execute("""DELETE from users where name = ?""", (username,))
                        else:
                            cursor.execute("""UPDATE users set invitations=?, Token='' where name=?""", (invitations_count, username,))
                        conn.commit()

                        flash(u'Inscription réalisée avec succés !', 'succes')
                        resp = redirect(url_for('loginlogout.login'))
                    else:
                        flash(u'Les mots de passe ne sont pas identiques !', 'error')
                        resp = render_template('inscription.html',
                                               signin_enable=app.config['SIGNIN_ENABLE'],
                                               token=token, hostname=hostname,
                                               url_inscription=url_inscription,
                                               MAIL_SERVER=MAIL_SERVER)
            else :

                resp = render_template('inscription.html',
                                       signin_enable=app.config['SIGNIN_ENABLE'],
                                       token=token, hostname=hostname,
                                       url_inscription=url_inscription,
                                       MAIL_SERVER=MAIL_SERVER)
    else:
        resp = redirect(BASE_URL, code=401)

    return resp