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

class FotoAPI
{
  
  public static function getFotoLink($pTyp, $pID, $pLfdNr, $pFoto = null, $pLinkPrefix = '')
  {
    if ($pID === '') {
      return '';
    }

    $info = static::getInfo($pTyp, $pID, $pLfdNr, $pFoto);
    $typ = $info['typ'];
    $id = $info['id'];
    $lfdNr = $info['lfdNr'];

    if (empty($id)) {
      return '';
    }

    $filename = static::getFotoFileName($typ, $id, $lfdNr);

    if (!file_exists(static::getPhysicalPath($typ) . $filename)) {
      return '';
    } else {
      return static::getLinkPath($typ, $pLinkPrefix) . $filename;
    }
  }

  private static function getFotoFilePath($pTyp, $pID, $pLfdNr, $pFoto = null)
  {
    if ($pID === '') {
      return '';
    }

    $info = static::getInfo($pTyp, $pID, $pLfdNr, $pFoto);
    $typ = $info['typ'];
    $id = $info['id'];
    $lfdNr = $info['lfdNr'];

    if (empty($id)) {
      return '';
    }

    $filename = static::getFotoFileName($typ, $id, $lfdNr);
    $pathWithFilename = static::getPhysicalPath($typ) . $filename;
    if (file_exists($pathWithFilename)) {
      return $pathWithFilename;
    } else {
      return '';
    }
  }

  public static function getFotoWidth($pTyp, $pID, $pLfdNr, $pFoto = null)
  {
    $filepath = static::getFotoFilePath($pTyp, $pID, $pLfdNr, $pFoto);

    if (empty($filepath)) {
      return '';
    } else {
      $imageSizeArray = getimagesize($filepath);

      return $imageSizeArray[0];
    }
  }

  public static function getFotoHeight($pTyp, $pID, $pLfdNr, $pFoto = null)
  {
    $filepath = static::getFotoFilePath($pTyp, $pID, $pLfdNr, $pFoto);

    if (empty($filepath)) {
      return '';
    } else {
      $imageSizeArray = getimagesize($filepath);

      return $imageSizeArray[1];
    }
  }

  private static function getInfo($pTyp, $pID, $pLfdNr, $pFoto = null)
  {
    if (is_null($pFoto) || strcmp(StringOperations::strtolower(get_class($pFoto)), 'foto') !== 0) {
      $dbwf = new DBWorkFoto();
      $id = $dbwf->getID($pTyp, $pID);
      if ($id === false) {
        return array('typ' => '', 'id' => '', 'lfdNr' => '');
      }
      $typ = $pTyp;
      $lfdNr = $pLfdNr;
    } else {
      $typ = $pFoto->getVarValue('typ');
      $id = $pFoto->getVarValue('id');
      $lfdNr = $pFoto->getVarValue('lfdNr');
    }

    return array('typ' => $typ, 'id' => $id, 'lfdNr' => $lfdNr);
  }

  
  public static function getFotoFileName($typ, $id, $lfdNr)
  {
    return $typ . '_' . $id . '_' . $lfdNr . '.jpg';
  }

  public static function getPhysicalPath($typ)
  {
    $dirs = ConstantOperations::getFotoTypArray();
    $pathTest = 'webbasys' . DIRECTORY_SEPARATOR . 'bilder' . DIRECTORY_SEPARATOR
                . $dirs[$typ] . DIRECTORY_SEPARATOR;
    if (defined('KUFERSQL_BILDER_BASEDIR') && KUFERSQL_BILDER_BASEDIR !== '') {
      $basePath = StringOperations::ensureTrailing(KUFERSQL_BILDER_BASEDIR, DIRECTORY_SEPARATOR);
    } else {
      $basePath = BASEDIR;
    }

    return $basePath . $pathTest;
  }

  public static function getLinkPath($typ, $linkPrefix = '')
  {
    
    $dirs = ConstantOperations::getFotoTypArray();
    $pathLink = $linkPrefix . 'bilder/' . $dirs[$typ] . '/';

    if (defined('KUFERWEB_BILDER_LINKPREFIX') && KUFERWEB_BILDER_LINKPREFIX !== '') {
      $pathLink = StringOperations::ensureTrailing(KUFERWEB_BILDER_LINKPREFIX, '/') . $pathLink;
    } else {
      if (TYPO3_CMS_RELPATH != '../') {
        $pathLink = '/' . TYPO3_CMS_RELPATH . 'webbasys/' . $pathLink;
      }
    }

    return $pathLink;
  }

  
  public static function augmentFilenameDimensionInfo($filename, $width, $height, $fileExtension = '.jpg')
  {
    return str_replace($fileExtension, "_w{$width}_h{$height}$fileExtension", $filename);
  }

  public static function augmentCropped($filename, $fileExtension = '.jpg')
  {
    return str_replace($fileExtension, '_c' . $fileExtension, $filename);
  }

  
  public static function convertPathToGenerated($filepath)
  {
    $sep = strpos($filepath, '\\') !== false ? '\\' : '/';

    return str_replace(
      'bilder' . $sep,
      'bilder' . $sep . 'generated' . $sep,
      $filepath
    );
  }

  
  public static function getFotoLinkForKuferTools(string $pTyp, $pNr, $pSuffix = 1): string
  {
    return self::getFotoLink($pTyp, $pNr, $pSuffix, null, '../webbasys/');
  }

  
  public static function getBelidToFotolinkMapping($pBelegungen)
  {
    $mapping = array();
    foreach ($pBelegungen as $belegung) {
      $mapping[$belegung->id] = FotoAPI::getFotoLinkForKuferTools('T', $belegung->tnr);
    }

    return $mapping;
  }

  
  public static function getFotoByVarname(string $pVarname, string $pType, $pID): ?array
  {
    if ($pID === '') {
      return null;
    }
    $matches = array();
    if (preg_match('/foto_([1-6])_(.+)/', $pVarname, $matches)) {
      $lfdNr = $matches[1];
      $pureVarname = $matches[2];
      $dbwF = new \DBWorkFoto();

      return array('foto' => $dbwF->getFoto($pType, $pID, $lfdNr), 'fotovarname' => $pureVarname);
    } elseif (preg_match('/foto_lfdnr_([1-6])_(.+)/', $pVarname, $matches)) {
      $lfdNr = $matches[1];
      $pureVarname = $matches[2];

      $dbwF = new \DBWorkFoto();
      $fotos = $dbwF->getFotoNummern($pType, $pID);
      if ($fotos === false || count($fotos) < $lfdNr) {
        return null;
      } else {
        return array('foto' => $dbwF->getFoto($pType, $pID, $fotos[$lfdNr - 1]), 'fotovarname' => $pureVarname);
      }
    } else {
      return null;
    }
  }

  public static function getLinkForPicSource($filename, $width, $height, $crop, $foto): string
  {
    $linkFilename = self::augmentFilenameDimensionInfo($filename, $width, $height);
    if ($crop) {
      $linkFilename = self::augmentCropped($linkFilename);
    }

    return self::convertPathToGenerated(self::getLinkPath($foto->getVarValue('typ')) . $linkFilename);
  }
}