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

namespace Kufer\Web\KuferTools\Utils\FilterSearch\Method;

use Kufer\Web\Classes\Dbfilter\ISQLFilter;

class BetweenTimeMethod extends SQLSearchFilterMethod
{
  
  public function __construct(string $fnApplyBeginn, string $fnApplyEnde)
  {
    parent::__construct(static function(ISQLFilter $filter, $value) use ($fnApplyBeginn, $fnApplyEnde): ISQLFilter {
      $result = $filter->all(static function(ISQLFilter $filter) use ($value, $fnApplyBeginn, $fnApplyEnde) {
        $filter = \call_user_func(array($filter, 'greaterEquals' . $fnApplyBeginn), $value);

        return \call_user_func(array($filter, 'lessEquals' . $fnApplyEnde), $value);
      });

      assert($result instanceof ISQLFilter);

      return $result;
    });
  }

  public function apply($filter, $value): ISQLFilter
  {
    if (\trim($value) === '' || !\DateTimeOperations::isValidTimeString($value)) { 
      return $filter;
    }

    return parent::apply($filter, $value);
  }

  public function fromRequest($value)
  {
    $value = trim($value);
    if ($value === '') {
      return null;
    }

    return $value;
  }
}