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

namespace Kufer\Web\Classes\Scripting3;

class ExprVar extends Expr
{
  
  public $varname;

  
  public $isInBody;

  
  public function __construct($varname, $isInBody = true)
  {
    $this->varname = $varname;
    $this->isInBody = $isInBody;
  }

  public static function getVariableFromHandler($varhandler, $vars, $cache)
  {
    if (is_array($vars)) {
      $varname = array();
      foreach ($vars as $var) {
        if (\is_string($var)) {
          $varname[] = $var;
        } else {
          $varname[] = $var->execute($varhandler, array(), $cache);
        }
      }
    } elseif (\is_string($vars)) {
      $varname = $vars;
    } else {
      $varname = $vars->execute($varhandler, array(), $cache);
    }

    $name = is_array($varname) ? $varname[0] : $varname;
    $joined = is_array($varname) ? implode(':', $varname) : $varname;

    if ($varhandler instanceof \Exportadapter) {
      $result = $varhandler->export->getVarValue($joined);
      if ($varhandler->sollVariableHtmlEncodedWerden($name)) {
        $result = \CleanOperations::cleanStringForHtml($result);
      } elseif ($varhandler->sollVariableHtmlPurifiedWerden($name)) {
        $result = \CleanOperations::cleanStringContainingHtml($result);
      }

      return $result;
    }

    if ($varhandler instanceof \ExportBasis) {
      return $varhandler->getVarValue($joined);
    }

    if (is_array($varhandler) && isset($varhandler[$name])) {
      return $varhandler[$name];
    }

    if (is_object($varhandler) && isset($varhandler->{$name})) {
      return $varhandler->{$name};
    }

    if ($varhandler instanceof \Datamodul) {
      if (is_array($varname) && isset($varname[1]) && $varname[1] != '') {
        $val = $varhandler->getVarValueEx($name, $varname[1]);
      } else {
        $val = $varhandler->getVarValue($name);
      }

      
      if ($val !== '') {
        return $val;
      }
    }

    return null;
  }

  public function toString(): string
  {
    $result = '';
    if (is_array($this->varname)) {
      $result .= (new \Kufer\Web\Classes\Stream\ArrayStream($this->varname))
        ->map(static function($e) {
          return \is_string($e) ? $e : $e->toString();
        })
        ->implode(':');
    } elseif (\is_string($this->varname)) {
      $result .= $this->varname;
    } else {
      $result .= $this->varname->toString();
    }

    return '{%' . $result . '%}';
  }

  public function toPHP(bool $isleaf, ParserHelper $phpcode, array $fnvars): string
  {
    $result = $phpcode->createVariable($this->varname, $fnvars, $this->isInBody);

    if ($isleaf) {
      $result = '$result.=' . $result . ';' . "\n";
    }

    return $result;
  }
}