import pytest

from django.db.models import Q

from pontoon.base.utils import aware_datetime
from pontoon.contributors.utils import users_with_translations_counts

from pontoon.test.factories import (
    EntityFactory,
    TranslationFactory,
    UserFactory,
)


@pytest.mark.django_db
def test_mgr_user_without_translations(translation_a, user_a, user_b):
    """
    Checks if user contributors without translations aren't returned.
    """
    assert translation_a.user == user_a
    top_contributors = users_with_translations_counts()
    assert user_a in top_contributors
    assert user_b not in top_contributors


@pytest.mark.django_db
def test_mgr_user_contributors_order(
    resource_b, locale_a,
):
    """
    Checks if users are ordered by count of contributions.
    """
    contributors = UserFactory.create_batch(size=5)
    entities = EntityFactory.create_batch(size=22, resource=resource_b)

    # create a list of contributors/entity for translations
    for i, count in enumerate([2, 4, 9, 1, 6]):
        for j in range(count):
            TranslationFactory.create(
                locale=locale_a, user=contributors[i], entity=entities[i],
            )

    # Ordered by approved count
    assert list(users_with_translations_counts()) == [
        contributors[i] for i in [2, 4, 1, 0, 3]
    ]


@pytest.mark.django_db
def test_mgr_user_contributors_limit(
    resource_a, locale_a,
):
    """
    Checks if proper count of user is returned.
    """
    contributors = UserFactory.create_batch(size=102)
    entities = EntityFactory.create_batch(size=102, resource=resource_a,)
    for i, contrib in enumerate(contributors):
        TranslationFactory.create(
            locale=locale_a, approved=True, user=contrib, entity=entities[i],
        )
    top_contributors = users_with_translations_counts()
    assert len(top_contributors) == 100


@pytest.mark.django_db
def test_mgr_user_translation_counts(
    resource_a, locale_a,
):
    """Checks if translation counts are calculated properly.

    Tests creates 3 contributors with different numbers translations