import { log } from '@gouvfr/dsfr-forge';
import { BadgesMap } from './badges-map.js';

class Badges {
  constructor(data) {
    let {ids, resource} = data;
    if (typeof ids === 'string') ids = ids.split(',');
    if (!Array.isArray(ids)) {
      log.error(`Badge must be a string or an array of strings, received: ${typeof ids}`);
      this._node = {};
      return;
    }
    const badges = ids.map(id => this._formatBadge(id, resource));
    if (badges.every(badge => Object.keys(badge).length === 0)) {
      this._node = {};
      return;
    }
    this._node = {
      type: 'htmlContainer',
      tagName: 'ul',
      classes: ['fr-badges-group', 'fr-mb-2v'],
      children: badges
    };
  }

  _getIconClasses (icon) {
    if (icon === false) {
      return ['fr-badge--no-icon'];
    }
    if (icon === true) {
      return [];
    }
    return [`fr-icon-${icon}`];
  }

  _formatBadge (id, resource) {
    const badgeData = BadgesMap.get(id);
    if (!badgeData) {
      log.error(`Unknown badge type: ${id}`);
      return {};
    }
    return {
      type: 'htmlContainer',
      tagName: 'li',
      children: [
        {
          type: 'paragraph',
          classes: [
            'fr-badge',
            `fr-badge--${badgeData.type}`,
            `fr-badge--${badgeData.size}`,
            ...this._getIconClasses(badgeData.icon)
          ],
          children: [
            {
              type: 'text',
              value: resource[id],
            }
          ]
        }
      ]
    };
  }

  get node () {
    return this._node;
  }
}

export { Badges };
