import React from 'react';
import PropTypes from 'prop-types';
import styles from './star-rating.module.scss';
import keygen from '~helpers/keygen';
import { getRating } from '~helpers/rating';

const StarRating = ({ numOfStars, rating, halfStars = true, active = true }) => {
  const renderFarm = () => {
    const output = [];
    const rate = getRating(rating);
    // generate stars
    for (let i = 1; i < numOfStars + 1; i += 1) {
      if (i <= rate) {
        output.push(
          <span className={styles.fullStar} key={keygen()}>
            {' '}
          </span>
        );
      } else if (halfStars && i - 0.5 === rate) {
        output.push(
          <span className={styles.halfStar} key={keygen()}>
            {' '}
          </span>
        );
      } else {
        output.push(
          <span className={styles.emptyStar} key={keygen()}>
            {' '}
          </span>
        );
      }
    }
    return output;
  };
  return (
    <div className={`${styles.starRatingContainer || ''} ${(!active && styles.inactive) || ''}`}>
      {renderFarm()}
    </div>
  );
};

StarRating.propTypes = {
  numOfStars: PropTypes.oneOf([5, 10]).isRequired,
  rating: PropTypes.oneOfType([PropTypes.array, PropTypes.number, PropTypes.string]).isRequired,
  halfStars: PropTypes.bool,
  active: PropTypes.bool,
};

export default StarRating;
