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

namespace Kufer\KuferTools\Utils\WssField;

use Kufer\Web\KuferTools\Utils\WssField\IWssField;

class WssField implements IWssField
{
  
  protected $datamodulColumn;

  
  public function __construct($datamodulColumn)
  {
    $this->datamodulColumn = $datamodulColumn;
  }

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

  public function getField($datamodulWert, bool $isFormular, string $requestPrefix = '')
  {
    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)
  {
    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()
  {
    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()) {
      return $this->getAlternativtext();
    } else {
      return $value;
    }
  }

  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 && $this->datamodulColumn->canedit == 1) {
      $datamodul = $this->getDatamodulName();
      $fieldname = $this->getFieldName();

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

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

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

  
  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;
    };

    $data->datamodul = $datamodulWert;
    $data->column = $this->getDmColumnMitDefaultBeruecksichtigt();
    $data->requestPrefix = $requestPrefix;
    if ($isFormular) {
      return new \Kufer\KuferTools\Basis\Presenter\WssPresenterFormular($data);
    } else {
      return new \Kufer\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)
  {
    return \CleanOperations::cleanStringForHtml($value);
  }

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

    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)
  {
    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->datamodulColumn->istext === \Kufer\KuferTools\Basis\Presenter\WssPresenterFormular::TEXTAREA && !$isFormular;
  }
}