<?php

namespace Rasb14\Dice;

/**
 * Generating histogram data.
 */
class Histogram
{
    /**
     * @var array $serie  The numbers stored in sequence.
     * @var int   $min    The lowest possible number.
     * @var int   $max    The highest possible number.
     */
    private $serie = [];
    private $min;
    private $max;

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

    /**
     * Return a string with a textual representation of the histogram.
     *
     * @return string representing the histogram.
     */
    public function getAsText()
    {
        $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">';
        for ($j = $this->min; $j <= $this->max; $j++) {
            if (isset($list[$j])) {
                $result .= '<li>' . $j . '. ';
                for ($i = 0; $i < $list[$j]; $i++) {
                    $result .= '*';
                }
                $result .= '</li>';
            } else {
                $result .= '<li>' . $j . '.</li>';
            }
        }
        $result .= '</ul>';

        return $result;
    }

    /**
     * Inject the object to use as base for the histogram data.
     *
     * @param HistogramInterface $object The object holding the serie.
     *
     * @return void.
     */
    public function injectData(HistogramInterface $object)
    {
        $this->serie = $object->getHistogramSerie();
        $this->min   = $object->getHistogramMin();
        $this->max   = $object->getHistogramMax();
    }
}
