from containers.models import Container
from preinfo.models import Preinfo


def filter_queryset_by_user(queryset, user):
    """
    Filters the queryset based on the user's line or company.
    If the user has a line, it filters by that line.
    If the user has a company, it filters by all lines associated with that company.
    """
    print(f'user: {user}, user company: {user.company}, user line: {user.line}, user type: {user.user_type}')
    if user.line:
        filtered = queryset.filter(line=user.line)
        print(f"Filtering by line: {user.line.id}, count: {filtered.count()}")
        return filtered
    elif user.company:
        company_lines = user.company.line_company.all()
        filtered = queryset.filter(line__in=company_lines)
        print(f"Filtering by company: {user.company.id}, count: {filtered.count()}")
        return filtered
    return queryset


def get_preinfo_by_number(number):
    """
    Retrieves a PreinfoModel instance by its container number.
    Returns None if no matching PreinfoModel is found.
    """
    try:
        return Preinfo.objects.get(container_number=number, received=False)
    except Preinfo.DoesNotExist:
        return None


def get_container_by_number(number):
    """
    Retrieves a Container instance by its number.
    Returns None if no matching Container is found.
    """
    try:
        return Container.objects.get(number=number, expedited=False)
    except Container.DoesNotExist:
        return None