import logging

from common.status import HTTP_401_UNAUTHORIZED, HTTP_404_NOT_FOUND
from flask import Blueprint, session
from flask_jwt_extended import jwt_required, get_jwt_identity
from median.database import decripte
from median.models import User, Profil
from peewee import DoesNotExist
from common.status import HTTP_500_INTERNAL_SERVER_ERROR

user_blueprint = Blueprint('user', __name__)

logger = logging.getLogger('median')


@user_blueprint.route('pin', methods=['GET'])
@jwt_required()
def get_pin_code():
    try:
        user_id = session['user_id']
        usr = User.get(pk=user_id)
        return {
            'pin': decripte(usr.password)
        }
    except DoesNotExist:
        return {'message': 'User.error.not_exist'}, HTTP_500_INTERNAL_SERVER_ERROR


@user_blueprint.route('', methods=['GET'])
@jwt_required()
def get():
    return _check_auth(None)


def _check_auth(ressource=None):
    """Check auth, return information if ok, otherwise 404"""
    identity = get_jwt_identity()

    if identity is None:
        return HTTP_401_UNAUTHORIZED

    try:
        usr = User.get(pk=identity)
        logger.info('User logged in. id: %s, name: %s, profil: %s' % (usr.pk, usr.username, usr.profil))

    except DoesNotExist:
        logger.error('User does not exist')
        return {'message': 'User does not exist'}, HTTP_404_NOT_FOUND

    profil_where_condition = (Profil.profil == usr.profil) & ((ressource is None) | (Profil.ressource == ressource))

    if session.get('device'):
        # TODO: Edit this is other devices are used
        profil_where_condition = profil_where_condition & (Profil.ressource.startswith('WEB_AIDEPLUS'))

    pro = Profil.select(
        Profil.visu, Profil.edit, Profil.ressource
    ).where(profil_where_condition)

    def apply(x):
        return {'visu': x.visu,
                'edit': x.edit,
                'resource': x.ressource}

    profils = list(map(apply, list(pro)))

    # Réécrire en utilisant usr.to_json() après mise a dispo dans la librairie Median
    return {
        'id': usr.pk,
        'name': usr.username,
        'profil': usr.profil,
        'desc': usr.description,
        'login': usr.login,
        'service': usr.service,
        'badge': usr.badge,
        'inventaire': usr.droit_inventaire,
        'stupefiant': usr.droit_stupefiant,
        'rights': profils,
        'visu': (0 if len(pro) == 0 else pro[0].visu),
        'edit': (0 if len(pro) == 0 else pro[0].edit),
        'maintenance': usr.maintenance,
        'email': usr.email,
        'lang': usr.lang,
        'avatar': usr.avatar,
        'device': session.get('device')
    }
