import re

from utils.rpc import gen
from gm_types.gaia import FILTER_WORD_TYPE
from gm_types.error import ERROR as CODES
from talos.services import AntiSpamService
from gm_rpcd.all import RPCDFaultException

def filterword_function(fw, content, isfilternum):
    """
    :param fw: 需要过滤的敏感词
    :param content: 需要过滤的内容
    :param isfilternum: 是否需要对数字进行过滤
    :return:
    """
    if isfilternum:
        if re.findall(u"\d{7,}", content) or any(word in content for word in fw):   #在此定义敏感词过滤方法
            return True
        else:
            return False
    else:
        if any(word in content for word in fw):   #在此定义敏感词过滤方法
            return True
        else:
            return False


def filterword_by_custom(filter_type, content, isfilternum=True):
    """
    :param filter_type: 需要按照什么样的敏感词类型过滤
    :param content: 需要过滤的内容
    :param isfilternum: 是否进行数字过滤
    :return:
    """
    try:
        fw = AntiSpamService.get_filtered_words(filter_type=filter_type)  # 获取需要敏感词列表
    except RPCDFaultException:
        gen(CODES.NEED_RECREATE)
    except Exception:
        gen(CODES.UNIVERSAL)

    if filter_type == FILTER_WORD_TYPE.TOPIC_REPLY:     #回复限制
        if filterword_function(fw, content, isfilternum):
            gen(CODES.CONTENT_CAN_NOT_CONTAIN_FORBID_WORD)
    elif filter_type == FILTER_WORD_TYPE.TOPIC_CONTENT:     #内容限制
        if filterword_function(fw, content, isfilternum):
            gen(CODES.TOPIC_CONTENT_CAN_NOT_CONTAIN_FORBID_WORD)
    elif filter_type == FILTER_WORD_TYPE.TOPIC_CHAT:    #私信限制
        if filterword_function(fw, content, isfilternum):
            gen(CODES.REPLY_CAN_NOT_CONTAIN_CONTACT)
