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

namespace Kufer\Web\Classes\Export\ExportCalculation;

class ExportCalcFotos extends ExportCalc
{
  public function resolveVar(string $varname, ?\Datamodul $datamodul = null, string $origVarname = ''): string
  {
    if (!is_a($datamodul, '\\Datamodul')) {
      return '';
    }
    if (is_null($datamodul->id)) {
      return '';
    }

    
    if (\StringOperations::substr(\StringOperations::strtolower($varname), 0, 10) === 'pic_source') {
      $parts = explode(':', $origVarname);
      if (count($parts) !== 2) {
        \Logger::logg('Ungültige Verwendung von {%..._pic_source[_crop][_2x]:width-height-mediaminwidth%}) - kein Parameter angegeben: ' . $origVarname, 3001);
      }

      return $this->handlePicSource($varname, $datamodul, $parts[1]);
    }

    if (\StringOperations::strstr($varname, 'komplett') !== false && \StringOperations::strstr($varname, 'crop') !== false) {
      return $this->getCroppedImgTag($varname, $datamodul, $origVarname);
    }

    switch (\StringOperations::strtolower($varname)) {
      case 'link':
        return \CleanOperations::cleanStringForHtml(\FotoAPI::getFotoLink(0, 0, 0, $datamodul));
      case 'untertitel':
      case 'beschreibung_bf':
        return \CleanOperations::cleanStringForHtml($datamodul->getVarValue(\StringOperations::strtolower($varname)));
      case 'untertitel_orig':
      case 'beschreibung_bf_orig':
        return \CleanOperations::cleanStringForHtml($datamodul->getVarValue(\StringOperations::strtolower(\StringOperations::substr($varname, 0, -5))));
      case 'alternativtext':
        $tmp = $datamodul->getVarValue('beschreibung_bf');
        if ($tmp != '') {
          return \CleanOperations::cleanStringForHtml($tmp);
        }

        return \CleanOperations::cleanStringForHtml($datamodul->getVarValue('untertitel'));
      case 'exists':
        $link = \FotoAPI::getFotoLink(0, 0, 0, $datamodul);

        return $link === '' ? '0' : '1';
      case 'width':
        return \FotoAPI::getFotoWidth(0, 0, 0, $datamodul);
      case 'height':
        return \FotoAPI::getFotoHeight(0, 0, 0, $datamodul);
      case 'komplett_responsive':
        $responsiveClass = ' img-responsive';
        
      case 'komplett':
        $link = \FotoAPI::getFotoLink(0, 0, 0, $datamodul);
        if ($link === '') {
          return '';
        }
        if (!isset($responsiveClass)) {
          $responsiveClass = '';
        }
        $types = \ConstantOperations::getFotoTypArray();
        $untertitel = $this->resolveVar('untertitel', $datamodul);
        if ($untertitel != '') {
          $untertitel = 'title="' . $untertitel . '"';
        }

        return \HTMLOperations::CreateImageTag(
          $link,
          $this->resolveVar('alternativtext', $datamodul),
          $types[$datamodul->getVarValue('typ')] . '_foto_'
          . $datamodul->getVarValue('lfdNr'),
          'wb_foto ' . $types[$datamodul->getVarValue('typ')] . '_foto' . $responsiveClass,
          $untertitel
        );
      default:
        return $this->getDefaultVarValue($varname, $datamodul);
    }
  }

  
  private function handlePicSource(string $varname, \Foto $foto, string $params): string
  {
    $info = $this->extractPicSrcInfo($params);
    $width = $info['width'];
    $height = $info['height'];
    $mediaMinWidth = $info['mediaMinWidth'];
    $filename = \FotoAPI::getFotoFileName($foto->getVarValue('typ'), $foto->getVarValue('id'), $foto->getVarValue('lfdNr'));
    $physicalFilename = \FotoAPI::getPhysicalPath($foto->getVarValue('typ')) . $filename;
    try {
      $resizer = new \Kufer\Web\Classes\Api\ImageResizer($physicalFilename);
    } catch (\Exception $e) {
      \Logger::logg('ImageResizer: ' . $e->getMessage(), 4020);

      return '';
    }
    $crop = \StringOperations::strpos($varname, '_crop') !== false;
    $resizer->crop = $crop;
    $resizer->resizeToDimension($width, $height);

    $link = \FotoAPI::getLinkForPicSource($filename, $width, $height, $crop, $foto);

    if (strpos($varname, '_2x') !== false) {
      $factor = 2;
      $wCur = $factor * $width;
      $hCur = $factor * $height;

      $resizer->resizeToDimension($wCur, $hCur);
      $link2 = \FotoAPI::getLinkForPicSource($filename, $wCur, $hCur, $crop, $foto);
      $result = \HTMLOperations::CreateSourceTag(array($link, "$link2 {$factor}x"), $mediaMinWidth);
    } else {
      $result = \HTMLOperations::CreateSourceTag(array($link), $mediaMinWidth);
    }

    return $result;
  }

  private function getCroppedImgTag(string $varname, $datamodul, $origVarname): string
  {
    $link = \FotoAPI::getFotoLink(0, 0, 0, $datamodul);
    if ($link === '') {
      return '';
    }
    $types = \ConstantOperations::getFotoTypArray();
    $untertitel = $this->resolveVar('untertitel', $datamodul);
    if ($untertitel != '') {
      $untertitel = 'title="' . $untertitel . '"';
    }
    $altText = $this->resolveVar('alternativtext', $datamodul);

    $parts = explode(':', $origVarname);
    $info = $this->extractPicSrcInfo($parts[1]);
    $filename = \FotoAPI::getFotoFileName($datamodul->getVarValue('typ'), $datamodul->getVarValue('id'), $datamodul->getVarValue('lfdNr'));
    $physicalFilename = \FotoAPI::getPhysicalPath($datamodul->getVarValue('typ')) . $filename;
    $resizer = new \Kufer\Web\Classes\Api\ImageResizer($physicalFilename);
    $resizer->crop = true;
    $resizer->resizeToDimension($info['width'], $info['height']);
    $link = \FotoAPI::getLinkForPicSource($filename, $info['width'], $info['height'], $resizer->crop, $datamodul);
    $srcset = '';
    if (\StringOperations::strstr($varname, '2x') !== false) {
      $factor = 2;
      $wCur = $factor * $info['width'];
      $hCur = $factor * $info['height'];
      $resizer->resizeToDimension($wCur, $hCur);
      $link2x = \FotoAPI::getLinkForPicSource($filename, $wCur, $hCur, $resizer->crop, $datamodul);
      $srcset = ' srcset="' . $link2x . ' 2x"';
    }

    $individ = $untertitel . $srcset;

    return \HTMLOperations::CreateImageTag(
      $link,
      $altText,
      $types[$datamodul->getVarValue('typ')] . '_foto_'
      . $datamodul->getVarValue('lfdNr'),
      'wb_foto ' . $types[$datamodul->getVarValue('typ')] . '_foto',
      $individ
    );
  }

  private function extractPicSrcInfo(string $param): array
  {
    $result = array();
    $info = explode('-', $param);
    $result['width'] = $info[0];
    $result['height'] = $info[1];
    $result['mediaMinWidth'] = $info[2] ?? '';

    return $result;
  }
}