# coding=utf-8

import json
from django.contrib.auth.models import Group, Permission
from rest_framework import serializers

from utils.exceptions import CustomError


class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id', 'name', )


class GroupSerializer(serializers.ModelSerializer):
    employees = serializers.SerializerMethodField()
    permissions = PermissionSerializer(many=True, read_only=True)

    def get_employees(self, obj):
        users = obj.user_set.all()
        data = []
        for user in users:
            data.append(user.employee.name)
        return data

    class Meta:
        model = Group
        fields = ('id', 'display_name', 'employees', 'permissions', 'name')

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['tenant'] = user.employee.tenant
        validated_data['create_user'] = user
        validated_data['name'] = validated_data['name'] + '@' + str(validated_data['tenant'].id)
        group = Group.objects.filter(name=validated_data['name']).first()
        if group:
            raise CustomError(u'名称为[%s]的权限组已存在' % validated_data['display_name'])

        permissions = self.context['request'].data.get('permissions', None)
        if permissions:
            permissions = json.loads(permissions)
        else:
            permissions = []
        instance = super(GroupSerializer, self).create(validated_data)
        instance.permissions.set(permissions)
        return instance

    def update(self, instance, validated_data):
        validated_data['name'] = validated_data['name'] + '@' + str(instance.tenant_id)
        group = Group.objects.filter(name=validated_data['name']).exclude(id=instance.id).first()
        if group:
            raise CustomError(u'名称为[%s]的权限组已存在' % validated_data['display_name'])
        permissions = self.context['request'].data.get('permissions', None)
        if permissions:
            permissions = json.loads(permissions)
        else:
            permissions = []
        instance = super(GroupSerializer, self).update(instance, validated_data)
        instance.permissions.set(permissions)
        return instance


class GroupDictSerializer(serializers.ModelSerializer):
    value = serializers.CharField(source='id', read_only=True)
    name = serializers.CharField(source='display_name', read_only=True)

    class Meta:
        model = Group
        fields = ('value', 'name', )
