from datetime import datetime


def path_and_rename(instance, filename):
    """Renames and paths document file on upload

    The filename is based on the primary key of the document object.
    If the primary key does not exist, the filename is the current datetime.

    When this function is called, the document's content type 
    has already gone through 2 checks

        1) File extension is validated against accepted extensions (.jpeg, .png, etc)
        2) FileValidator checks the content of the file's header 
            (malicious code might be masked with an accepted extension)

    Parameters
    ----------
    instance : Document instance
        instance of Document object
    filename : str
        string of uploaded file
    
    Returns
    -------
    str
        Constructed path and name for file to upload to S3

    """
    upload_to = 'documents'
    ext = filename.split('.')[-1]
    if instance.pk:
        filename = f'{instance.pk}'
    else:
        t = datetime.now()
        filename = f'{t.year}-{t.month}-{t.day}-{t.hour}-{t.minute}-{t.second}-{t.microsecond}'
    return f'{upload_to}/{filename}.{ext}'