# coding=utf-8

import re
from gm_serializer import serializers

from utils.rpc import RPCMixin
from helios.rpc import RPCFaultException


class BlacklistValidator(RPCMixin):
    def __call__(self, value):
        try:
            r = self.call_rpc('api/user/in_blacklist', user_id=value)
        except:
            return False

        if r:
            raise serializers.ValidationError("User in blacklist.")


class FilterWordValidator(RPCMixin):

    def __init__(self, filter_type=None):
        self.filter_type = filter_type

    def __call__(self, value):
        if re.findall('\d{7,}', value):
            raise serializers.ValidationError("Content contains sensitive words.")

        try:
            r = self.call_rpc('api/filterWord/list', filter_type=self.filter_type)
        except RPCFaultException:
            return False
        if value in r:
            raise serializers.ValidationError("Content contains sensitive words.")


class RepeatedValidator(object):

    def __init__(self, model_cls, field_name):
        self.model_cls = model_cls
        self.field_name = field_name

    def __call__(self, value):

        obj = self.model_cls.objects.last()
        if getattr(obj, self.field_name, None) == value:
            raise serializers.ValidationError("%s repeated." % self.model_cls.__class__)



