/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

class SyliusRating {
  constructor(container, settings) {
    this.container = container;
    this.settings = settings;

    if (this.container) {
      this.ratingMax = Number(this.container.dataset.maxRating) || 5;
      this.ratingAverage = Number(this.container.dataset.averageRating) || Number(this.container.dataset.rating) || 0;

      this.render();
    }
  }

  render() {
    this.container.innerHTML = '';
    // eslint-disable-next-line no-undef
    const renderElement = document.createElement('div');

    // eslint-disable-next-line no-plusplus
    for (let i = 1; i <= this.ratingMax; i++) {
      // eslint-disable-next-line no-undef
      const element = document.createElement('span');
      element.dataset.ratingValue = i;
      element.addEventListener('click', this.changeInputValue.bind(this));

      if (i <= this.ratingAverage) {
        element.innerHTML = '<i class="fas fa-star active"></i>';
      } else {
        element.innerHTML = '<i class="fas fa-star disabled"></i>';
      }

      renderElement.appendChild(element);
    }
    this.container.appendChild(renderElement);
  }

  changeInputValue(e) {
    const value = Number(e.currentTarget.dataset.ratingValue);
    this.ratingAverage = value;
    this.container.dataset.ratingAverage = value;
    this.render();
    this.settings.onRate(value);
  }
}

export default SyliusRating;
