# coding=utf-8

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 utils import get_remote_addr
from utils.exceptions import CustomError

from apps.log.models import BizLog

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


class JWTSerializer(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 not user.is_administrator():
                    msg = u"非工作帐号，禁止登录！"
                    BizLog.objects.addnew(user, BizLog.INSERT, u'非管工作账号[%s]尝试登录系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)
                if not user.is_active:
                    msg = u'禁用帐户，禁止登录！'
                    BizLog.objects.addnew(user,  BizLog.INSERT,u'禁用帐户[%s]尝试登录系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)
                BizLog.objects.addnew(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,
                    'name': user.name or '',
                }
            else:
                msg = u'账号或者密码错误!'
                BizLog.objects.addnew(None, BizLog.INSERT, u'登录失败[%s][%s],IP[%s]' % (attrs[self.username_field], attrs['password'], get_remote_addr(self.request)))
                raise serializers.ValidationError(msg)
        else:
            msg = u'必须包含“{username field}”和“password.”'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


class UserSerializer(serializers.ModelSerializer):
    type = serializers.IntegerField(read_only=True)
    password = serializers.CharField(write_only=True, allow_blank=True)

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        validated_data['type'] = User.ADMINSTRATOR
        if validated_data['password'].strip() == '':
            raise CustomError(u'密码不能为空！')
        instance = super(UserSerializer, self).create(validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    def update(self, instance, validated_data):
        instance.update_item(validated_data)
        return instance
    