import re

from django.template.loader import render_to_string
from django.utils.html import strip_tags

from containers.models import Container
from preinfo.models import Preinfo
from django.conf import settings
from django.core.mail import send_mail, EmailMessage


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


CALC_STRING = "0123456789A.BCDEFGHIJK.LMNOPQRSTU.VWXYZ"

def check_container_number_validity(container_number):
    if not re.search(r"[A-Z]{4}[0-9]{7}", container_number):
        return False
    subtotal = 0
    delta = 1
    for i in range(0, 10):
        subtotal = subtotal + CALC_STRING.find(container_number[i]) * delta
        delta = delta * 2
    subtotal = (subtotal % 11) % 10
    if not subtotal == CALC_STRING.find(container_number[10]):
        return False
    return True


ADMIN_USER_EMAIL= settings.ADMIN_USER_EMAIL
EMAIL_HOST_USER = settings.EMAIL_HOST_USER

def send_test_email(user_email, urls):
    subject='Welcome to Our Platform'
    html_message = render_to_string('email.html', {
        'site_name': 'Our Platform',
        'user_email': user_email,
        'link1': urls['pay_epay'],
        'link2': urls['pay_credit_card'],
    })
    plain_message = strip_tags(html_message)

    email = EmailMessage(
        subject=subject,
        body=html_message,
        from_email=EMAIL_HOST_USER,
        to=[user_email],
    )
    email.content_subtype = 'html'  # This tells Django to send HTML email
    email.send()