import { UrlArgs } from '~/types/interfaces'
import BaseHook from '~/services/data/hooks/baseHook'

/**
 * Base class for an object which support hooks
 */
abstract class Hookable {
  protected hooks: Array<typeof BaseHook> = []; // how could we replace 'any'?

  /**
   * Iterate over the available hooks and invoke the ones
   * that support the given args
   */
  protected async triggerHooks (args: UrlArgs) {
    for (const Hook of this.sortedHooks()) {
      if (Hook.support(args)) {
        await new Hook().invoke(args)
      }
    }
  }

  /**
   * Sort the available hooks by priority
   * @private
   */
  private sortedHooks (): Iterable<any> {
    return this.hooks.sort(function (a, b) {
      if (a.priority > b.priority) { return 1 }
      if (a.priority < b.priority) { return -1 }
      return 0
    })
  }
}

export default Hookable
