<?php
/**
 * Created by PhpStorm.
 * User: sale
 * Date: 23.10.17.
 * Time: 18.10
 */

namespace Intellex\Generator\Text;

/**
 * Generates a single paragraph.
 * Class ParagraphGenerator
 *
 * @package Intellex\AutoPopulate\Generator
 */
class ParagraphGenerator extends SentenceGenerator {

	/** @var int $min Minimum sentences in one paragraph. */
	private $min;

	/** @var int $max Maximum sentences in one paragraph. */
	private $max;

	/** @var float $ol Chance of generating ordered list in paragraph in range of 0-1. */
	private $ol;

	/** @var float $ul Chance of generating unordered list in paragraph in range of 0-1. */
	private $ul;

	/**
	 * ParagraphGenerator constructor.
	 *
	 * @param float $ol  Chance of generating ordered list in paragraph in range of 0-1.
	 * @param float $ul  Chance of generating unordered list in paragraph in range of 0-1.
	 * @param int   $min Minimum sentences in one paragraph.
	 * @param int   $max Maximum sentences in one paragraph.
	 */
	public function __construct($ol = 0.09, $ul = 0.09, $min = 8, $max = 12) {
		parent::__construct();
		$this->min = $min;
		$this->max = $max;
		$this->ol = $ol;
		$this->ul = $ul;
	}

	/**
	 * Generates random paragraph.
	 *
	 * @return string
	 */
	public function generateValue() {
		$randParagraph = '';
		$length = rand($this->min, $this->max);
		$olIndex = 1;
		$olLength = $length;
		if (static::should($this->ol)) {
			while ($length--) {
				$randParagraph .= "{$olIndex}. " . parent::generateValue() . "\n";
				$olIndex++;
				if ($olIndex === $olLength + 1) {
					break;
				}
			}
			return $randParagraph;
		} elseif (static::should($this->ul)) {
			while ($length--) {
				$randParagraph .= "* " . parent::generateValue() . "\n";
				$olIndex++;
				if ($olIndex === $olLength + 1) {
					break;
				}
			}
			return $randParagraph;
		} else {
			while ($length--) {
				$randParagraph .= " " . parent::generateValue();
			}
			return $randParagraph;
		}

	}

	/**
	 * Get true or false by supplied probability.
	 *
	 * @param float $value The probability of true, form 0 - 1.
	 *
	 * @return bool True to execute, false to skip/
	 */
	protected static function should($value) {
		$rand = mt_rand(0, 1000000) / 1000000;
		return $rand < $value;
	}

}