import { toPlural } from '@vizality/util/string';
import { HTTP } from '@vizality/constants';
import { get } from '@vizality/http';
import Events from 'events';

/**
 * @extends Events
 */
export default class CommunityManager extends Events {
  constructor () {
    super();
    this.plugins = new Map();
    this.themes = new Map();
  }

  /**
   *
   */
  get count () {
    return this.plugins.size + this.themes.size;
  }

  /**
   *
   */
  get pluginsCount () {
    return this.plugins.size;
  }

  /**
   *
   */
  get themesCount () {
    return this.themes.size;
  }

  /**
   *
   * @param {string} addonId Addon ID
   * @returns
   */
  get (addonId, type) {
    return this[toPlural(type)].get(addonId);
  }

  /**
   *
   * @param {string} addonId Addon ID
   * @returns {boolean}
   */
  has (addonId, type) {
    return this[toPlural(type)].has(addonId);
  }

  /**
   *
   * @returns {Promise<void>}
   */
  async initialize () {
    /**
     * Gets all of the addon repos currently active on the addon community organization.
     */
    const response = await get(`${HTTP.API}/addons`);
    const addons = await response.body;
    const { plugins, themes } = addons;
    Object.values(plugins)
      .map(plugin => this.plugins.set(plugin.addonId, plugin));
    Object.values(themes)
      .map(theme => this.themes.set(theme.addonId, theme));
  }
}
