from django.db.models import Q

from payments.models import ContainerTariffPeriod, AdditionalFees


def calculate_charges(container):
    days = (container.expedited_on.date() - container.received_on.date()).days + 1
    total = 0

    size = '20' if container.container_type.length == 20 else '40'

    tariff = ContainerTariffPeriod.objects.get(
        Q(to_days__gt=days) | Q(to_days__isnull=True),
        container_size=size,
        from_days__lte=days,
    )

    fees = AdditionalFees.objects.first()
    storage_charge = days * float(tariff.daily_rate)

    if container.container_type.container_type == 'reefer':
        storage_charge += days * float(fees.reefer_daily_supplement)

    if container.swept:
        total += float(fees.sweeping_fee)
    if container.washed:
        total += float(fees.fumigation_fee)

    total += storage_charge

    return {
        'days': days,
        'storage_charge': storage_charge,
        'services_charge': total - storage_charge,
        'total': total,
    }
