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.
    """

    if user.line:
        return queryset.filter(line=user.line)
    elif user.company:
        company_lines = user.company.line_company.all()
        return queryset.filter(line__in=company_lines)
    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