# -*- coding: utf8 -*-
from .default import (
    execute_query,
)
import datetime #<- will be used to set default dates on models

def get_users_all(request):
    query = "SELECT id, name, strftime('%d/%m/%Y %H:%M:%S', last_logged) as last_login FROM users ORDER BY name;"
    results = results = request.dbsession.execute(query).fetchall()
    return results


def get_users_by_name(request, name ):
    query = "SELECT * FROM users WHERE name=:name;"
    results = request.dbsession.execute(query, {'name': name}).first()
    return results


def delete_user(request, id):
    query = "DELETE FROM users WHERE id = :id ;"
    execute_query(request, query, {'id': id})
    return 

def groupfinder(userid, request):

    if userid:
        # user name is 'admin' ?
        if userid == 'admin':
            return ['group:administrators']
        else:
            return []  # it means that userid is logged in 
    else:
        # it returns None if userid isn't logged in
        return None

def update_user(request, name, new_values):
    # formater les champs
    s = ''
    for param in new_values.keys():
        if s:
            s += ",%s=:%s" % (param, param)
        else:
            s = "%s=:%s" % (param, param)

    if name == '0':
        query = "INSERT INTO users (name, password) VALUES ('{0}', '{1}')".format(new_values['name'], new_values['password'])
    else:
        new_values['name'] = name
        query = "UPDATE users SET %s WHERE name = :name;" % s
    execute_query(request, query, new_values)

def update_last_connection(request, id, password_hash):
    """Update last connection for login """
    last_logged = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    query = "UPDATE users SET last_logged=:last_logged, password=:password_hash WHERE id=:id;"
    execute_query(request, query, {'id': id, 'last_logged': last_logged, 'password_hash': password_hash})
