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

declare(strict_types = 1);

namespace Kufer\Web\Classes\Dbfilter;


class KurstageSQLFilter extends BasicSQLFilter
{
  public const FILTER_OPTION_KURSE = 'kurse';
  public const FILTER_OPTION_DOZENTEN = 'dozenten';
  public const FILTER_OPTION_KURSE_FAECHER = 'kurseFaecher';

  protected function __construct()
  {
    parent::__construct();

    $this->registerDb('Id', 'id', static::TYPE_INTEGER);
    $this->registerDb('KursId', 'knr', static::TYPE_STRING);
    $this->registerDb('Datum', 'datum', static::TYPE_DATE);
    $this->registerDb('Ort', 'ort', static::TYPE_STRING);
    $this->registerDb('BeginnZeit', 'zeit_beg', static::TYPE_TIME);
    $this->registerDb('EndeZeit', 'zeit_ende', static::TYPE_TIME);
    $this->registerDb('ShownOnRaumanzeige', 'ranzprognoanz', static::TYPE_BOOLEAN_NOT_W_F);
    $this->registerDb('Minuten', 'minuten', static::TYPE_INTEGER);
    $this->registerDb('Text', 'text', static::TYPE_STRING);
    $this->registerDb('ShownOnDozentenTool', 'nodoztool', static::TYPE_BOOLEAN_NOT_W_F);
    $this->registerDb('ShownOnTeilnehmerTool', 'notntool', static::TYPE_BOOLEAN_NOT_W_F);
    $this->registerDb('ShownOnWeb', 'noweb', static::TYPE_BOOLEAN_NOT_W_F); 
    
    $this->registerDb('KurseFachId', 'fachid', static::TYPE_INTEGER);
    
    $this->registerDb('Status', 'ausf', static::TYPE_STRING);
    $this->registerDb('DozentId', 'dnr', static::TYPE_INTEGER);
    $this->registerDb('RuestzeitVor', 'rzvor', static::TYPE_INTEGER);
    $this->registerDb('RuestzeitNach', 'rznach', static::TYPE_INTEGER);
    $this->registerDb('RuestzeitInfoVor', 'rzvorinfo', static::TYPE_STRING);
    $this->registerDb('RuestzeitInfoNach', 'rznachinfo', static::TYPE_STRING);
  }

  protected function addToBuilder(): callable
  {
    return static function(\SelectQueryBuilder $toAdd, \SelectQueryBuilder $result): \SelectQueryBuilder {
      $var = $result->uniqueVar();

      return $result->and(":table:.id IN (:$var:)")
        ->paramSelectQuery($var, $toAdd);
    };
  }

  public function getTablePraeffix(): string
  {
    return 'kt';
  }

  public function equalsId($id): IFilter
  {
    $this->applyFilterCurrent(
      static::FILTER_OPTION_ID,
      SQLFilterUtils::filterEqualsIdInt('id', $id)
    );

    return $this;
  }

  public function inId(iterable $ids): IFilter
  {
    $this->applyFilterCurrent(
      static::FILTER_OPTION_ID,
      SQLFilterUtils::filterInIdInt('id', $ids)
    );

    return $this;
  }

  public function equalsOrtId(int $ortId): IFilter
  {
    $dbwKursorte = new \DBWorkKursorte();
    $ort = $dbwKursorte->getKursort($ortId);

    $this->equalsOrt($ort->mktext); 

    return $this;
  }

  
  public function inStatus($status): IFilter
  {
    if (\is_string($status)) {
      $status = \StringOperations::str_split($status);
    }

    $realStatusAry = array();
    foreach ($status as $singleStatus) {
      if ($singleStatus === '-'
          || $singleStatus === ' '
          || $singleStatus === '') { 
        \array_push($realStatusAry, ' ', '');
      } else {
        $realStatusAry[] = $singleStatus;
      }
    }

    $this->applyRegisteredCall($this->getRegisteredCallByName('Status'), 'in', array($realStatusAry), false, null);

    return $this;
  }

  public function applyKurseFilter(\Kufer\Web\Classes\Dbfilter\KurseSQLFilter $filter): KurstageSQLFilter
  {
    $filter->makeImmutable();

    if ($filter->isEmpty()) {
      return $this;
    }

    $this->applyFilterCurrent(static::FILTER_OPTION_KURSE, function(\SelectQueryBuilder $builder) use ($filter): \SelectQueryBuilder {
      $dbwKurse = \DBWorkKurse::getDefaultInstance($builder->getDBOperation()->dbnr);
      $kurseBuilder = $dbwKurse->findByFilterQuery($filter)
        ->select('k.nr');

      $var = $builder->uniqueVar();

      return $builder
        ->and(":table:.knr IN (:$var:)")
        ->paramSelectQuery($var, $kurseBuilder);
    });

    return $this;
  }

  public function applyDozentenFilter(\Kufer\Web\Classes\Dbfilter\DozentenSQLFilter $filter): KurstageSQLFilter
  {
    $filter->makeImmutable();

    if ($filter->isEmpty()) {
      return $this;
    }

    $this->applyFilterCurrent(static::FILTER_OPTION_DOZENTEN, function(\SelectQueryBuilder $builder) use ($filter): \SelectQueryBuilder {
      $dbwKurse = \DBWorkDozenten::getDefaultInstance($builder->getDBOperation()->dbnr);
      $dozentenBuilder = $dbwKurse->findByFilterQuery($filter)
        ->select(':table:.nr');

      $var = $builder->uniqueVar();

      return $builder
        ->and(":table:.dnr IN (:$var:)")
        ->paramSelectQuery($var, $dozentenBuilder);
    });

    return $this;
  }

  public function applyKurseFaecherFilter(KurseFaecherSQLFilter $filter): IFilter
  {
    $filter->makeImmutable();

    if ($filter->isEmpty()) {
      return $this;
    }

    $this->applyFilterCurrent(static::FILTER_OPTION_KURSE_FAECHER, function(\SelectQueryBuilder $builder) use ($filter): \SelectQueryBuilder {
      $builderKurseFaecher = $filter->createBuilder($builder->getDBOperation())
        ->select('id')
        ->from('kurs_fach')
        ->and('kurs_fach.knr = kt.knr'); 

      $var = $builder->uniqueVar();

      return $builder
        ->and(":table:.fachid IN (:$var:)")
        ->paramSelectQuery($var, $builderKurseFaecher);
    });

    return $this;
  }
}