# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from tastypie import http
from tastypie.resources import Resource
from tastypie.utils import trailing_slash
from tastypie.exceptions import ImmediateHttpResponse
from api.utils import jwt_token
import simplejson as json

'''
'''
class JWTResource(Resource):
    class Meta:
        allowed_methods = ['post']
        resource_name = 'auth'

    '''
    '''
    def prepend_urls(self):
        return [
            url(r'^%s/get_token%s$' % (self._meta.resource_name, trailing_slash), self.wrap_view('get_token'), name="api_get_token"),
            url(r'^%s/check_token%s$' % (self._meta.resource_name, trailing_slash), self.wrap_view('check_token'), name="api_check_token"),
        ]

    '''
    '''
    def get_token(self, request, **kwargs):
        self.method_check(request, allowed=self._meta.allowed_methods)

        # Check content type
        if request.content_type != 'application/json':
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        # Check body
        if not request.body:
           raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        # Check required parameters
        body = json.loads(request.body)
        if 'username' not in body or 'password' not in body:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        # Check user
        token = jwt_token.create_token(body['username'], body['password'])
        if not token:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        bundle = self.build_bundle(obj={
            'token': token,
            'username': body['username']
        }, request=request)

        return self.create_response(request, bundle.obj)

    '''
    '''
    def check_token(self, request, **kwargs):
        self.method_check(request, allowed=self._meta.allowed_methods)

         # Check content type
        if request.content_type != 'application/json':
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        # Check body
        if not request.body:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        # Check required parameters
        body = json.loads(request.body)
        if 'token' not in body:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        (user, ok) = jwt_token.check_token(body['token'])

        # Check status
        response_status = (401, 200)[bool(ok)]
        if response_status == 401:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        bundle = self.build_bundle(obj={
            'token': body['token'],
            'username': user.username
        }, request=request)

        return self.create_response(request, bundle.obj)