def invalidate_stats_cache(resource, language, **kwargs):
    """
    Invalidate template caches and handle the updating of the persistent
    stats.
    """

    is_source = False
    if not language or language == resource.source_language:
        is_source = True
        language = resource.source_language

    team_languages = get_project_teams(resource.project).values_list(
            'language', flat=True)

    if not is_source:
        # Get or create new RLStat object
        rl, created = RLStats.objects.get_or_create(resource=resource,
            language=language)
        rl.update( kwargs['user'] if kwargs.has_key('user') else None)
        # Check to see if the lang has zero translations and is not a team
        # lang. If yes, delete RLStats object
        if rl.translated == 0 and rl.language.id not in\
          team_languages:
            rl.delete()
    else:
        rl, created = RLStats.objects.get_or_create(resource=resource,
            language=language)
        # Source file was updated. Update all language statistics
        stats = RLStats.objects.filter(resource=resource)
        for s in stats:
            s.update(kwargs['user'] if kwargs.has_key('user') else None)
            if s.translated == 0 and s.language.id not in\
              team_languages:
                s.delete()

        # Update resource wordcount and total entities
        resource.update_total_entities(save=False)
        resource.update_wordcount(save=True)

    invalidate_object_templates(resource, language, **kwargs)
dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/resources/handlers.py/invalidate_stats_cache/original