<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Pdf\Helper;

class ImageByPath extends RenderObject
{
  public const PX_FACTOR_MM = 0.3553;

  
  private $path;

  
  private $islogo;

  
  private $useImageSize;

  public function __construct($fpdf, string $logoFileNamesOrPath, bool $isLogo, bool $useImageSize = true)
  {
    parent::__construct($fpdf);

    $this->islogo = $isLogo;
    if (file_exists(($logoFileNamesOrPath))) {
      $this->path = $logoFileNamesOrPath;
    } else {
      $this->path = \PDFLogo::getLogoFilePath(array($logoFileNamesOrPath));
    }

    $this->useImageSize = $useImageSize;

    assert(!empty($this->path));
  }

  private function getLogoWidth(): float
  {
    
    
    
    
    $toolSettings0 = \ToolSettingsAPI::getToolSettings(0);
    $preferredImageSize = $toolSettings0->pdflisteLogoWidth;
    if ($preferredImageSize <= 0) {
      $preferredImageSize = 150;
    }

    return $preferredImageSize * self::PX_FACTOR_MM;
  }

  private function getRealImageSize(): array
  {
    list(0 => $width, 1 => $height) = getimagesize($this->path);

    return array($width * self::PX_FACTOR_MM, $height * self::PX_FACTOR_MM);
  }

  private function getImageSize(): array
  {
    list($width, $height) = $this->getRealImageSize();
    if ($this->islogo) {
      $preferredImageSize = $this->getLogoWidth();
      if ($width > $preferredImageSize) {
        $imageWidth = $preferredImageSize;
        $imageHeight = $preferredImageSize / $width * $height;
      } else {
        $imageWidth = $width * self::PX_FACTOR_MM;
        $imageHeight = $height * self::PX_FACTOR_MM;
      }

      return array($imageWidth, $imageHeight);
    }

    return array($width, $height);
  }

  public function getAutoWidth(): ?float
  {
    return $this->useImageSize ? $this->getImageSize()[0] : null;
  }

  public function getAutoHeight(): ?float
  {
    return $this->useImageSize ? $this->getImageSize()[1] : null;
  }

  public function render(): void
  {
    $this->context(function() {
      if (static::DEBUG_ALL) {
        $this->drawOutline();
      }

      $width = $this->getComputedWidth();
      $height = $this->getComputedHeight();
      list($imgWidth, $imgHeight) = $this->getImageSize();

      if ($this->useImageSize) {
        list($width, $height) = array($imgWidth, $imgHeight);
      } else {
        $widthByHeight = $height * $imgWidth / $imgHeight;
        $heightByWidth = $width * $imgHeight / $imgWidth;
        if ($widthByHeight > $width) {
          $height = $heightByWidth;
        } else {
          $width = $widthByHeight;
        }
      }

      $x = $this->getComputedX() ?? $this->fpdf->GetX();
      $y = $this->getComputedY() ?? $this->fpdf->GetY();
      $this->fpdf->Image($this->path, (int)$x, (int)$y, (int)$width, (int)$height);
    });
  }
}