from time import monotonic

from django.core.cache import cache


LOCK_EXPIRE = 60 * 10  # 10 minutes


class MemCacheLock:
    def __init__(self, lock_id, oid):
        self.lock_id = lock_id
        self.oid = oid

        self.timeout_at = monotonic() + LOCK_EXPIRE - 3

    def __enter__(self):
        self.status = cache.add(self.lock_id, self.oid, LOCK_EXPIRE)
        return self.status

    def __exit__(self, *args, **kwargs):
        if monotonic() < self.timeout_at and self.status:
            cache.delete(self.lock_id)
