<?php

namespace Rasb14\Dice;

/**
 * A trait implementing histogram for integers.
 */
trait HistogramTrait
{
    /**
     * @var array $serie  The numbers stored in sequence.
     */
    private $serie = [];

    /**
     * Get the serie.
     *
     * @return array with the serie.
     */
    public function getHistogramSerie()
    {
        return $this->serie;
    }

    /**
     * Print out the histogram, default is to print out only the numbers
     * in the serie, but when $min and $max is set then print also empty
     * values in the serie, within the range $min, $max.
     *
     * @param int $min The lowest possible integer number.
     * @param int $max The highest possible integer number.
     *
     * @return string representing the histogram.
     */
    public function printHistogram(int $min = null, int $max = null)
    {
        $list = [];
        foreach ($this->serie as $value) {
            if (isset($list[$value])) {
                $list[$value]++;
            } else {
                $list += [$value => 1];
            }
        }

        ksort($list);

        $result = '<ul style="list-style-type:none">';
        if (isset($min) && isset($max)) {
            for ($j = $min; $j <= $max; $j++) {
                if (isset($list[$j])) {
                    $result .= '<li>' . $j . '. ';
                    for ($i = 0; $i < $list[$j]; $i++) {
                        $result .= '*';
                    }
                    $result .= '</li>';
                } else {
                    $result .= '<li>' . $j . '.</li>';
                }
            }
        } else {
            foreach ($list as $key => $value) {
                $result .= '<li>' . $key . '. ';
                for ($i = 0; $i < $value; $i++) {
                    $result .= '*';
                }
                $result .= '</li>';
            }
        }
        $result .= '</ul>';

        return $result;
    }
}
