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

namespace Kufer\Web\Classes\Ampel\Renderer;

class Ampel7Renderer extends AmpelRendererTextOrGrafisch
{
  private $fallbackToAmpel6;

  private static $xmlCache;

  private const AMPEL_PACKS_PATH = 'layout/kursampeln/';

  public function __construct(bool $fallbackToAmpel6 = true)
  {
    if (is_null(static::$xmlCache)) {
      static::$xmlCache = new \Kufer\Utils\Cache(array($this, 'getXml'));
    }
    $this->fallbackToAmpel6 = $fallbackToAmpel6;
  }

  protected function getAmpelGrafisch(int $status, \ToolSettings $settings): string
  {
    $status += 1; 

    $ampelStyle = $settings->ampelstyle;
    if ($ampelStyle == '') {
      $this->handleFallback($status - 1);
    }

    $xml = call_user_func(static::$xmlCache, $ampelStyle);

    $title = $settings->{'optionstatustext' . $status};

    if (isset($xml->sprite)) {
      if (!isset($xml->pictures->{'status' . $status})) {
        $this->handleFallback($status - 1);
      }
      $status_xml = $xml->pictures->{'status' . $status}->attributes();
      $sprite = $xml->sprite->attributes();

      $height = $status_xml['height'] ?? $sprite['default_height'];
      $width = $status_xml['width'] ?? $sprite['default_width'];
      $x = $status_xml['x'] ?? '0';
      $y = $status_xml['y'] ?? '0';

      $style = $this->getBackgroundCss($ampelStyle, $sprite['img'], $x, $y)
              . 'height: ' . $height . 'px;'
              . 'width: ' . $width . 'px;';

      return \HTMLOperations::CreateImageTag(
        self::AMPEL_PACKS_PATH . 'trans.png', 
        $title, 
        '', 
        '', 
        'title="' . \CleanOperations::cleanStringForHtml($title) . '" style="' . \CleanOperations::cleanStringForHtml($style) . '"' 
      );
    } else {
      if (!isset($xml->pictures->{'status' . $status})) {
        $this->handleFallback($status - 1);
      }

      return \HTMLOperations::CreateImageTag(
        self::AMPEL_PACKS_PATH . $ampelStyle . '/' . $xml->pictures->{'status' . $status}, 
        $title, 
        '', 
        '', 
        'title="' . \CleanOperations::cleanStringForHtml($title) . '"' 
      );
    }
  }

  private function handleFallback(int $status)
  {
    if ($this->fallbackToAmpel6) {
      $renderer = \Kufer\Web\Classes\Ampel\Renderer\AmpelRendererFactory::getAmpel6Renderer(false);

      return $renderer->create($status);
    } else {
      return '';
    }
  }

  private function getAmpelPackHttpLink(string $ampelStyle)
  {
    if (TYPO3_CMS_USED) {
      $link = \CleanOperations::cleanStringForHtml(TYPO3_CMS_RELPATH) . 'webbasys/' . self::AMPEL_PACKS_PATH;
    } else {
      $link = self::AMPEL_PACKS_PATH;
    }
    $link .= $ampelStyle . '/';

    return $link;
  }

  public function getXml(string $ampelStyle) 
  {
    $ampelPackPath = BASEDIR . 'webbasys/' . self::AMPEL_PACKS_PATH . $ampelStyle;

    if (!is_dir($ampelPackPath) || !file_exists($ampelPackPath . DIRECTORY_SEPARATOR . 'settings.xml')) {
      throw new \Exception('Ampel-Verzeichnis ' . $ampelPackPath . ' existiert nicht, oder settings.xml fehlt!');
    }

    $xml = simplexml_load_file($ampelPackPath . DIRECTORY_SEPARATOR . 'settings.xml');
    if ($xml === false) {
      throw new \Exception('XML konnte nicht gelesen werden');
    }

    return $xml;
  }

  private function getBackgroundCss(string $ampelStyle, string $spriteImg, string $xPx, string $yPx): string
  {
    $ampelPackHttpLink = $this->getAmpelPackHttpLink($ampelStyle);
    $rootPath = '';
    if (!T3_BASEURL) {
      $rootPath = preg_replace('/index.php$/i', '', \RequestOperations::getVarValueServer('PHP_SELF'));
    }

    return "background:url('{$rootPath}{$ampelPackHttpLink}{$spriteImg}') {$xPx}px {$yPx}px;";
  }
}