"""API."""

from flask import Blueprint, jsonify, request

from tagio.models.user import User
from tagio.extensions import csrf_protect

from . import user

__all__ = ('user',)

blueprint = Blueprint('api',
                      __name__,
                      url_prefix='/api/v<string:version>')


@blueprint.route('/login', methods=['POST'])
@csrf_protect.exempt
def login(version):
    """Login.

    login to retrieve token.
    """
    if version == '1':
        return _login_first_version()

    return jsonify({'code': 1, 'msg': 'Invalid version'})


def _login_first_version():
    username = request.form.get('username')
    password = request.form.get('password')

    if username is None or password is None:
        return jsonify({'code': 2, 'msg': 'Invalid parameter'})

    username = username.strip().lower()

    obj = User.query.filter(User.username == username).first()
    if obj is None:
        return jsonify({'code': 2, 'msg': 'Invalid parameter'})

    flag = obj.check_password(password)
    if not flag:
        return jsonify({'code': 2, 'msg': 'Invalid parameter'})

    if not obj.active:
        return jsonify({'code': 2, 'msg': 'Invalid parameter'})

    return jsonify({'code': 0, 'token': obj.get_auth_token()})
