import logging
import re

from django.contrib.auth.models import Group, Permission
from django.utils.translation import gettext
from rest_framework import serializers

from assets.models.assets import Asset
from console.models import (Connection)
from core.serializers import ModelLocalizedSerializer, DateTimeLocalizedField

RE_GROUPNAME = re.compile('[@+!#$%^&*()<>?/|}{~:]')
logger_info = logging.getLogger('console.user.info')
_log = logging.getLogger()


class AllPermsSerializer(ModelLocalizedSerializer):
    name = serializers.SerializerMethodField('get_name')

    class Meta:
        model = Permission
        fields = ['codename', 'name', 'content_type']

    def get_name(self, obj):
        return gettext(obj.name)


class GroupNameSerializer(ModelLocalizedSerializer):
    class Meta:
        model = Group
        fields = ['name']

    def validate_name(self, value):
        """ Method for validating the name, which was passed to the serializer
        @param value: name from the serializer (pass through: serializer.data)
        @return: name of the group
        """
        # Check for special symbols in group name
        if RE_GROUPNAME.search(value) is not None:
            raise serializers.ValidationError(gettext('Incorrect group name format. Try another'))

        return value


class CelerySerializer(serializers.Serializer):
    task_id = serializers.UUIDField()
    finished = serializers.BooleanField(required=False)
    result = serializers.IntegerField(required=False)


# Network map serializers for ConnectionInfoSerializer
# Asset connection info serializer
class ConnectionAssetInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Asset
        fields = ['pk', 'name', 'ip']


# Connection serializer
class ConnectionSerializer(serializers.ModelSerializer):
    src_asset = ConnectionAssetInfoSerializer()
    dst_asset = ConnectionAssetInfoSerializer()
    updated = DateTimeLocalizedField()
    created = DateTimeLocalizedField()

    class Meta:
        model = Connection
        fields = ['src_asset', 'dst_asset', 'connection_protocol', 'created', 'updated']
