__author__ = 'RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

import string

from flask import session

from . import jsonrpc
from .. import app, lib, models


@jsonrpc.method('auth.login')
def login(username: str, password: str) -> bool:
    user = models.db_session.query(
        models.User
    ).filter(
        models.User.name == username,
        models.User.password == lib.get_hash_password(
            password,
            app.config['SECRET_KEY']
        ),
        models.User.disabled == False # noqa E712
    ).first()
    if user is None:
        raise ValueError
    session['logged_in'] = True
    session['user_id'] = user.id
    return True


@jsonrpc.method('auth.logout')
def logout() -> bool:
    session.clear()
    return True


@jsonrpc.method('auth.register')
def login_register(username: str, password: str) -> bool:
    """Регистрация
    """
    if len(username) < 4 or len(username) > 25:
        raise ValueError('Длина логина от 4 до 25 символов')
    if len(password) < 4 or len(password) > 150:
        raise ValueError('Длина пароля от 4 до 150 символов')
    for char in username:
        if char not in string.ascii_letters + string.digits:
            raise ValueError

    user = models.db_session.query(
        models.User
    ).filter(
        models.User.name == username
    ).first()
    if user:
        raise ValueError('Пользователь с таким логином уже существует')

    newuser = models.User(username)
    newuser.password = lib.get_hash_password(
        password,
        app.config['SECRET_KEY']
    )
    models.db_session.add(newuser)
    models.db_session.commit()

    return True
