# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.utils.crypto import constant_time_compare
from jwt import DecodeError
import jwt

'''
'''
def create_token(username, password):
    # Check if exists jwt key
    if not settings.JWT_SECRET_KEY:
        return None

    user = authenticate(username=username, password=password)

    # Check user authentication
    if not user:
        return user

    payload = {
        'uid': user.id,
        'password': user.password
    }

    return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm='HS256')

'''
'''
def explode_token(token):
    if not token:
        return False

    # Normalize token
    if token.startswith(settings.JWT_PREFIX_HEADER):
        prefix_length = len(settings.JWT_PREFIX_HEADER) 
        token = token[prefix_length + 1:]

    # Check if exists jwt key
    if not settings.JWT_SECRET_KEY:
        return None

    payload = None

    try:
        payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithm='HS256')
    except DecodeError:
        return False

    # Check payload parameters
    if 'uid' not in payload or 'password' not in payload:
        return False
    
    return payload

'''
'''
def get_user(token):
    payload = explode_token(token)

    user = User.objects.get(pk=payload['uid'])

    return user

'''
'''
def get_username(token):
    user = get_user(token)

    # Check if exists user
    if not user:
        return user

    return user.name

'''
'''
def check_token(token):
    payload = explode_token(token)
     
    if not payload:
        return (None, False)

    user = User.objects.get(pk=payload['uid'])

    # Check if exists user
    if not user:
        return (None, False)

    return (user, constant_time_compare(user.password, payload['password']))
