<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\HTML;

use Kufer\Web\Classes\Stream\ArrayStream;
use Kufer\Web\Classes\Stream\IterableStream;

class TextToHtmlConverter implements \Kufer\Web\Classes\Converter\TextConverter, \Kufer\Web\Classes\Converter\HTMLConverter
{
  private $text;

  public function __construct(string $text)
  {
    $this->text = $text;
  }

  public function toText(): string
  {
    return $this->text;
  }

  public function toHTML(): string
  {
    $text = strtr($this->text, array(
      "\r\n" => "\n",
      "\r" => "\n"
    ));

    $lastLine = null;

    return (new ArrayStream(explode("\n", $text)))
      ->map(static function(string $line): string {
        $trimmed = trim($line);
        if ($trimmed === '') {
          return '';
        }

        return $line;
      })
      ->filter(static function(string $line) use (&$lastLine): string {
        if ($lastLine !== '' && $line === '') {
          $lastLine = '';

          return false;
        }

        $lastLine = $line;

        return true;
      }, new ArrayStream(array()))
      ->map(static function(string $line): string {
        if ($line === '') {
          return '<br/>';
        }

        return '<p>' . \StringOperations::htmlentities($line) . '</p>';
      })
      ->implode("\n");
  }
}