'''
Presumably, all database implementations will need to have a heartbeat that reports what indexes are still in use and
clears out stale ones. This module contains functions to facilitate that.
'''

import logging

from threading import Event, Thread


logger = logging.getLogger(__name__)


class IntervalThread(Thread):

  def __init__(self, delay_s, fn):
    super().__init__(daemon=True)
    self._delay_s = delay_s
    self.call = fn
    self._stop_flag = Event()
    self.start()

  def cancel(self):
    self._stop_flag.set()

  def run(self):
    while not self._stop_flag.wait(self._delay_s):
      try:
        self.call()
      except:
        logger.error('Interval function failed: %s' % self.call)


def interval(delay_s):
  # A decorator that runs the wrapped function every 'delay_s' seconds. The decorated function can no longer be called
  # directly - it serves as an accessor to the underlying thread object, on which you can call the original function
  # using the 'call' property or 'cancel' it.
  #
  # Example usage:
  # @interval(1)
  # def test():
  #   print('Every second')
  #
  # test.cancel()
  def decorator(fn):
    return IntervalThread(delay_s, fn)
  return decorator
