# coding=utf-8
import json
from django.contrib.auth import get_user_model, authenticate

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.settings import api_settings
from apps.foundation.models import BizLog
from apps.account import tenant_log
from utils import get_remote_addr
from utils.exceptions import CustomError

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class TenantJWTSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if user.status != User.INSERVICE:
                    msg = u'禁用帐户，禁止登录'
                    tenant_log(user, BizLog.INSERT,u'禁用帐户[%s]尝试登录系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                permissions = list(user.get_all_permissions())

                payload = jwt_payload_handler(user)
                tenant_log(user, BizLog.INSERT, u'[%s]登录系统,IP[%s]' % (user.username,get_remote_addr(self.request)))

                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username,
                    'permissions': permissions
                }
            else:
                msg = u'账号或者密码错误!'
                raise serializers.ValidationError(msg)
        else:
            msg = u'必须包含“{username field}”和“password.'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)

class EmployeeSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(source='date_joined', read_only=True)
    status_text = serializers.SerializerMethodField()

    def get_status_text(self, obj):
        return User.STATUS_CHOICES[obj.status][1]

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        instance = super(EmployeeSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if 'user' in validated_data:
            instance.user.update_item(validated_data['user'])
            validated_data.pop('user')
        instance = super(EmployeeSerializer, self).update(instance, validated_data)
        return instance