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

namespace Kufer\Web\KuferTools\Utils\FilterSearch;

use Kufer\Web\Classes\Dbfilter\ISQLFilter;
use Kufer\Web\Classes\Dbfilter\KursorteSQLFilter;
use Kufer\Web\KuferTools\Utils\FilterSearch\Method\SQLSearchFilterMethod;

class KursorteUebersichtSearchFilter extends ToolSearchFilter
{
  public function __construct()
  {
    parent::__construct();

    $this->addSearch(
      'gebaeude',
      new class() extends SQLSearchFilterMethod {
        public function __construct()
        {
          parent::__construct(static function(ISQLFilter $filter, $value): ISQLFilter {
            assert($filter instanceof KursorteSQLFilter);
            $filter->inGebaeude(array_map(static function($str) {
              return $str === '-' ? '' : $str;
            }, $value));

            return $filter;
          });
        }

        public function apply($filter, $value): ISQLFilter
        {
          if (!\is_array($value)) {
            return $filter;
          }

          $value = array_filter($value);
          if (empty($value)) {
            return $filter;
          }

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

        public function fromRequest($value)
        {
          if (empty($value) || !\is_array($value)) {
            return null;
          }

          return array_filter($value);
        }
      }
    );
  }

  public function createRequestKey(string $searchMapKey): string
  {
    return $searchMapKey;
  }
}