import { selectorFamily } from 'recoil';
import intervalTime from './intervalTime';

/**
 * Read-only selector family for subscribing to a `Date` object at a certain
 * updating interval. It uses the `intervalTime` selector internally to limit
 * recomputations, meaning that whatever subscribes to this will get a new
 * `Date` object _at most_ each expiration of the interval.
 *
 * If no period is provided or if the period is invalid (less than one, falsey,
 * etc.), then the period is automatically set to `1`, which means that the
 * interval will update _each time the `now` atom updates_. In general you
 * should _always_ provide an explicit interval value.
 */
const interval = selectorFamily({
  key: 'test.selectors.interval',
  get: period => ({
    get
  }) => {
    const time = get(intervalTime(period));
    if (!time) return undefined;
    return new Date(time);
  }
});
export default interval;