import math
from datetime import timedelta

from zope.interface import implements

from documentlibrary.core import interfaces

class DocumentAlertDates(object):
    implements(interfaces.IDocumentAlertDates)
    
    def __init__(self, context):
        self.context = context
        
    def getExpiryAlertDate(self):
        """Calculate the alert date based on expiry and available dates.

        This calculation is based on the difference between expiry and
        available dates. 
        """
        difference = self.context.expirydate - self.context.availabledate
        if difference >= timedelta(days=140):
            d = timedelta(days=14)
        elif difference > timedelta(days=30):
            d = timedelta(days=int(math.ceil(difference.days / 10.)))
        elif difference > timedelta(days=10):
            d = timedelta(days=3)
        else:
            return None # no expiry date, no alert sent
        return self.context.expirydate - d
