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

namespace Kufer\Web\KuferTools\Utils\WssField;

use Kufer\Web\KuferTools\Basis\UseCaseBuilder\ToolSection;

class WssField implements IWssField
{
  
  protected $datamodulColumn;
  
  protected $toolSection;
  
  protected $toolSettings;

  
  public function __construct(ToolSection $toolSection, \ToolSettings $toolSettings, $datamodulColumn)
  {
    $this->toolSection = $toolSection;
    $this->toolSettings = $toolSettings;
    $this->datamodulColumn = $datamodulColumn;
  }

  
  public function setDatamodulColumn(\Column $datamodulColumn): void
  {
    $this->datamodulColumn = $datamodulColumn;
  }

  public function getField($datamodulWert, bool $isFormular, string $requestPrefix = ''): string
  {
    if ($isFormular && $this->datamodulColumn->canedit) {
      return $this->getFieldBearbeitbar($datamodulWert, $isFormular, $requestPrefix);
    } else {
      return $this->getFieldNichtBearbeitbar($datamodulWert, $isFormular, $requestPrefix);
    }
  }

  public function isMandatory(): bool
  {
    return $this->datamodulColumn->mandatory_field && $this->datamodulColumn->canedit;
  }

  
  protected function isMandatoryValueEmpty($value): bool
  {
    return trim($value) === '';
  }

  
  public function isValid($value, bool $checkPflichtfelder = true): bool
  {
    if ($this->isMandatoryValueEmpty($value)) {
      return !($checkPflichtfelder && $this->isMandatory());
    }

    $valType = \SightBuilder::getInputClassNameByField($this->getFieldName(), 2);
    switch ($valType) {
      case 'val_int':
        return \CleanOperations::isInt($value);
      case 'val_float':
        return \CleanOperations::isFloatMitKomma($value);
      case 'val_date':
        return \DateTimeOperations::isValidDate($value); 
      case 'val_time':
        return \DateTimeOperations::getValidTimeString($value) == $value; 
      case 'val_einsnull':
        return in_array($value, array(0, 1));
      case 'val_jn':
        return in_array($value, array('j', 'J', 'n', 'N'));
      case 'val_bankdaten':
        
        return true; 

      case 'val_email':
        $validation = \ValidierungBasis::getInstance();
        
        return $validation->isValidVar('email', $value) === true;
    }

    return true;
  }

  
  public function getDatamodulName(): string
  {
    return $this->datamodulColumn->datamodul;
  }

  
  public function getFieldName(): string
  {
    return $this->datamodulColumn->fieldname;
  }

  protected function getDatamodulAndFieldName(): string
  {
    return $this->getDatamodulName() . '_' . $this->getFieldName();
  }

  
  public function getTitle(): string
  {
    return $this->datamodulColumn->title;
  }

  
  public function getHtmlEncodedValue($datamodulWert, bool $isFormular): string
  {
    $value = $this->encodeValue($this->getValue($datamodulWert, $isFormular) ?? '');
    if ($this->isValueEmpty($value) && $this->showAlternativtext()) {
      if (!$isFormular) {
        return $this->getAlternativtext();
      } else {
        return '';
      }
    } else {
      return $value;
    }
  }

  public function createPlaceholder(): string
  {
    if ($this->showAlternativtext()) {
      return $this->getAlternativtext();
    } else {
      return $this->datamodulColumn->title;
    }
  }

  public function isDatamodulValueEmpty($datamodulWert, bool $isFormular): bool
  {
    $value = $this->encodeValue($this->getValue($datamodulWert, $isFormular) ?? '');

    return !($this->isValueEmpty($value) && $this->showAlternativtext());
  }

  public function isValueEmpty($value): bool
  {
    return is_null($value) || trim($value) == '' || $value == '0' || $value == '0,00';
  }

  protected function showAlternativtext()
  {
    return \StringOperations::substr($this->datamodulColumn->wenn_leer ?? '', 0, 6) == '[TEXT]';
  }

  protected function getAlternativtext()
  {
    return \StringOperations::substr($this->datamodulColumn->wenn_leer ?? '', 6);
  }

  
  public function inPost(string $requestPrefix = ''): bool
  {
    return \PostOperations::isDefined(($requestPrefix === '' ? '' : $requestPrefix . '_') . $this->getDatamodulAndFieldName());
  }

  
  public function getValueFromPost(string $requestPrefix = '')
  {
    return \PostOperations::getVarValue(($requestPrefix === '' ? '' : $requestPrefix . '_') . $this->getDatamodulAndFieldName());
  }

  public function getChangedInfo($columnValues, $changedDm, $changedFields): array
  {
    if ($this->datamodulColumn->accesslevel == 2 && (bool)$this->datamodulColumn->canedit) {
      $datamodul = $this->getDatamodulName();
      $fieldname = $this->getFieldName();

      if (isset($columnValues[$datamodul][$fieldname])) {
        $origValue = $changedDm->getVarValueEx($fieldname, $datamodul);
        $newValue = $this->getPostValueToVarValue($columnValues, $columnValues[$datamodul][$fieldname]);
        if ($this->areValuesDifferent($origValue, $newValue)) {
          $changedDm->setValue2VarEx($fieldname, $newValue, $datamodul);
          $changedFields[] = $fieldname;
        }
      }
    }

    return array('changed' => $changedDm, 'changedFields' => $changedFields);
  }

  
  protected function getPostValueToVarValue($columnValues, $value)
  {
    return $value;
  }

  protected function areValuesDifferent($origValue, $newValue): bool
  {
    return $origValue != $newValue;
  }

  
  protected function getValue($datamodulWert, $isFormular = false)
  {
    return $datamodulWert->getVarValueEx($this->getFieldName(), $this->getDatamodulName());
  }

  
  protected function getFieldBearbeitbar($datamodulWert, $isFormular, string $requestPrefix = '')
  {
    return $this->getFieldFromSight($datamodulWert, $isFormular, $requestPrefix);
  }

  
  protected function getFieldNichtBearbeitbar($datamodulWert, $isFormular, string $requestPrefix = '')
  {
    return $this->getFieldFromSight($datamodulWert, $isFormular, $requestPrefix);
  }

  
  protected function getFieldFromSight($datamodulWert, $isFormular, string $reqestPrefix = '')
  {
    $presenter = $this->getWssPresenter($datamodulWert, $isFormular, $reqestPrefix);

    return $presenter->getField();
  }

  
  private function getWssPresenter($datamodulWert, $isFormular, string $requestPrefix = '')
  {
    $data = new class() {
      public $datamodul;
      public $column;
      public $requestPrefix;
      public $toolSection;
      public $toolSettings;
    };

    $data->datamodul = $datamodulWert;
    $data->column = $this->getDmColumnMitDefaultBeruecksichtigt();
    $data->requestPrefix = $requestPrefix;
    $data->toolSettings = $this->toolSettings;
    $data->toolSection = $this->toolSection;
    if ($isFormular) {
      return new \Kufer\Web\KuferTools\Basis\Presenter\WssPresenterFormular($data);
    } else {
      return new \Kufer\Web\KuferTools\Basis\Presenter\WssPresenter($data);
    }
  }

  
  protected function _getFieldname($field)
  {
    return $field->datamodul . '_' . $field->fieldname;
  }

  protected function encodeValue($value)
  {
    return $this->htmlEncode($value);
  }

  
  protected function htmlEncode($value): string
  {
    return \CleanOperations::cleanStringForHtml($value);
  }

  public function getDmColumnMitDefaultBeruecksichtigt(): \Column
  {
    $datamodulColumn = clone($this->datamodulColumn);
    $datamodulColumn->istext = $this->getType();

    if (!is_null($this->getDefaultMaxLength())
        && (empty($datamodulColumn->maxlength) || $datamodulColumn->maxlength > $this->getDefaultMaxLength())) {
      $datamodulColumn->maxlength = $this->getDefaultMaxLength();
    }
    if (empty($datamodulColumn->fontsize)) {
      $datamodulColumn->fontsize = $this->getDefaultFontSize();
    }

    return $datamodulColumn;
  }

  
  public function getDefaultMaxLength(): ?int
  {
    return null;
  }

  
  public function getDefaultFontSize(): int
  {
    return 100;
  }

  
  protected function purifyHtml($value): string
  {
    return \CleanOperations::cleanStringContainingHtml($value);
  }

  protected function dontEncode($value)
  {
    return $value;
  }

  public function getMandatoryClass(\Column $datamodulColumn): string
  {
    if ($datamodulColumn->mandatory_field) {
      return 'form_mandatory';
    }

    return '';
  }

  public function shouldBreakLines(bool $isFormular): bool
  {
    return $this->getType() === \Kufer\Web\KuferTools\Basis\Presenter\WssPresenterFormular::TYPE_TEXTAREA && !$isFormular;
  }

  protected function getType(): int
  {
    return $this->datamodulColumn->istext;
  }

  public function getDependencies(): array
  {
    return array();
  }
}