"""
<Description>
  Allows for actions to sleep until
  either:
    (A) a timer fires
    (B) an event happens

<Usage>
  SleepLock() - constructor
  sleep_lock.acquire() - get the lock
  sleep_lock.release() - give it up
  sleep_lock.sleep(timeout) - set an event to release us
  sleep_lock.wakeup() - break out of timeout early to release

<Example>
  include sleep_lock.repy

  # setup
  lock = SleepLock()
  lock.acquire()
  lock.sleep(1)

  # blocks for one second
  lock.acquire() 

  # continue on ...  
"""  
class SleepLock:

  def __init__(self):
    self.timer = None
    self.lock = getlock()

  def acquire(self):
    self.lock.acquire()

  def release(self):
    self.lock.release()

  def sleep(self, timeout):
    self.timer = settimer(timeout, self.wakeup, ())

  def wakeup(self):
    if self.timer:
      canceltimer(self.timer) 
      self.timer = None                   
      self.release()

