from pathlib import Path
import time
import pickle


def lock(filepath, wait=2, retries=2):
    """
    Create a lockfile for a specified file.
    If the file is already locked, wait for a specified number of seconds.
    Retry a maximum number of times before timing out.
    """

    # Create a path for the lock file
    f_lock = filepath + '.lock'

    for _ in range(retries):
        # If the file is currently locked
        if Path(f_lock).exists():
            # Wait a few seconds and check again
            time.sleep(wait)
        else:
            # Write a lock file
            with open(f_lock, 'wb') as file:
                pickle.dump(f_lock, file)
                break  
    else:
        # If the file is still locked after maximum retries raise an exception
        if Path(f_lock).exists():
            raise TimeoutError("The specified file is locked. If you believe this to be wrong, please delete file {0}".format(f_lock))
    
    return True