from flask import Flask
import sqlite3
import os
import string
import random

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


DATABASE = app.config['DATABASE']
DOSSIER_PERSO = app.config['DOSSIER_APP']
DATABASE = app.config['DATABASE']

def append_to_log(log_line, user):
    log_file=os.path.join(DOSSIER_PERSO, user, "log.txt")
    logs=open(log_file, "r")
    tmp=logs.read()
    logs.close()
    log=open(log_file, "w")
    log.write(log_line)
    log.write(tmp)
    log.close()



def email_disp(email):
    disp = True
    unique_at = len(email.split('@'))
    if len(email) < 80 and unique_at == 2:
        conn = sqlite3.connect(DATABASE) # Connexion à la base de donnée
        cursor = conn.cursor() # Création de l'objet "curseur"

        # Caractères non autorisés dans la RFC #822
        invalid_char = { '(', ')', '<', '>', ',', ';', ':', '"', '[', ']', '|', 'ç', '%', '&' }

        for character in invalid_char:
            if character in email:
                disp=False

        cursor.execute("""SELECT mail FROM users WHERE mail=?""", (email,))
        testmail = cursor.fetchall()
        if testmail and disp:
            disp = False

        if disp:
            cursor.execute("""SELECT alias FROM users""")
            aliases = cursor.fetchall()
            for alist in aliases:
                for alias in alist:
                    if alias:
                        if email in alias:
                            disp=False



    else:
        disp = False

    return disp


def valid_passwd(password):
    if '"' in password or "&" in password:
        return False
    else:
        return True



def valid_token_register(token):
    valid = True
    print(token)
    if len(token) != 30:
        valid = False

    if valid:
        conn = sqlite3.connect(DATABASE)
        cursor = conn.cursor()
        cursor.execute("""SELECT name, invitations FROM users where Token=?""", (token,))
        tmp = cursor.fetchone()
        conn.close()
        print (tmp)
        if tmp:
            valid = True
        else:
            valid = False
    print(valid)
    return valid

#Génère un token de 30 caratères aléatoires
def gen_token():
    letters = random.choices(string.ascii_letters, k=20)
    digits = random.choices(string.digits, k=10)
    sample = ''.join(random.sample(digits + letters, 30))

    return sample