# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.utils import trailing_slash
from django.conf.urls import url
from django.contrib.auth.models import User
from api.validations.user_validation import UserValidation
from api.resources.group_resource import GroupResource
from api.utils.jwt_authentication import JWTAuthentication
import simplejson as json

'''
'''
class UserResource(ModelResource):
    groups = fields.ToManyField(GroupResource, 'groups')

    class Meta:
        queryset = User.objects.all()
        always_return_data = True
        validation = UserValidation()
        authentication = JWTAuthentication()

    '''
    '''
    def prepend_urls(self):
        return [
            url(r'^(?P<resource_name>%s)/(?P<%s>.*?)/change_password%s$' % (self._meta.resource_name, self._meta.detail_uri_name, trailing_slash), self.wrap_view('change_password'), name='api_change_password')
        ]

    '''
    '''
    def change_password(self, request, **kwargs):
        self.method_check(request, ['post'])
        self.is_authenticated(request)

        # Check content type
        if request.content_type != 'application/json':
            return self.create_response(request, {
                'error_message': 'request is not json'
            })

        # Check body
        if not request.body:
            return self.create_response(request, {
                'error_message': 'request body is empty'
            })
        
        # Check if password is present in body
        if not 'password' in request.body:
            return self.create_response(request, {
                'error_message': 'password is not provided'
            })

        body = json.loads(request.body)
        user = User.objects.get(pk=kwargs.get('pk'))

        user.set_password(body['password'])

        bundle = self.build_bundle(obj=user, request=request)
        bundle = self.full_dehydrate(bundle)

        return self.create_response(request, {
            self._meta.resource_name: bundle
        })

    '''
    '''
    def save(self, bundle, skip_errors=False):
        if bundle.via_uri:
            return bundle

        self.is_valid(bundle)

        # If bundle has errors send this reponse
        if bundle.errors and not skip_errors:
            raise ImmediateHttpResponse(response=self.error_response(bundle.request, bundle.errors))

        # If object data is not persist create django auth user
        if bundle.obj._state.adding:
            user = User.objects.create_user(bundle.data['username'], bundle.data['email'], bundle.data['password'])
            user.first_name = bundle.data.get('first_name', '')
            user.last_name = bundle.data.get('last_name', '')

            bundle.obj = user
        
        bundle.data['groups'] = bundle.data.get('groups', [])

        if bundle.obj.pk:
            self.authorized_update_detail(self.get_object_list(bundle.request), bundle)
        else:
            self.authorized_create_detail(self.get_object_list(bundle.request), bundle)

        self.save_related(bundle)

        obj_id = self.create_identifier(bundle.obj)

        if obj_id not in bundle.objects_saved or bundle.obj._state.adding:
            bundle.obj.save()
            bundle.objects_saved.add(obj_id)

        m2m_bundle = self.hydrate_m2m(bundle)
        self.save_m2m(m2m_bundle)
        
        return bundle