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

namespace Kufer\Web\Classes\Search;


class KursSuggestions
{
  
  private $dbUtil;
  
  private $tokenizer;
  
  private $dbwKurse;
  
  private $tool4Settings;

  public function __construct(
    ?\Kufer\Web\Classes\Db\DBDirectUtility $pDbUtil = null,
    ?Tokenizer $pTokenizer = null,
    ?\KursWebUebersichtSettings $pTool4Settings = null,
    ?\DBWorkKurse $pDbwKurse = null
  ) {
    if ($pDbUtil === null) {
      $this->dbUtil = new \Kufer\Web\Classes\Db\DBDirectUtility();
    } else {
      $this->dbUtil = $pDbUtil;
    }
    if (is_null($pTokenizer)) {
      $this->tokenizer = new Tokenizer();
    } else {
      $this->tokenizer = $pTokenizer;
    }
    if (is_null($pTool4Settings)) {
      $this->tool4Settings = \ToolSettingsAPI::getToolSettings(4);
    } else {
      $this->tool4Settings = $pTool4Settings;
    }
    if (is_null($pDbwKurse)) {
      $this->dbwKurse = new \DBWorkKurseINetAktiv();
      $this->dbwKurse->newSearch();
      $this->dbwKurse->fromobject->semester = $this->tool4Settings->semlist;
    } else {
      $this->dbwKurse = $pDbwKurse;
    }
  }

  
  public function indexKursData()
  {
    if (!$this->dbUtil->checkTableExistsOrCreate(
      'web_suggestions',
      'CREATE TABLE web_suggestions (suggestion varchar(50) NOT NULL, UNIQUE KEY `suggestion` (`suggestion`));'
    )) {
      throw new \Exception('Die Tabelle mit den Suchvorschlaegen existiert nicht und konnte auch nicht angelegt werden');
    }

    $this->dbUtil->truncateTable('web_suggestions');

    $inputData = $this->getContentFromTableKurseToIndex();

    
    
    foreach ($inputData as $kursData) {
      $tokensOfThisItem = $this->tokenizer->tokenize($kursData);
      $this->writeSuggestionsToDb($tokensOfThisItem);
    }
  }

  private function getContentFromTableKurseToIndex()
  {
    $where = $this->dbwKurse->getWhereForGetKurseByCategoryLimit();
    if ($where !== '' && !\StringOperations::startsWith(trim($where), 'WHERE', false)) {
      $where = ' WHERE ' . $where;
    }

    return $this->dbUtil->selectSeveralFieldsConcatenated(
      'kurse k',
      'nr',
      $this->getStichwortSearchFieldsFromKursTableToIndex(),
      $where
    );
  }

  
  private function getStichwortSearchFieldsFromKursTableToIndex()
  {
    $fields = $this->getFieldsForStichwortSearch();

    return array_filter($fields, function($item) {
      return strpos($item, '.') === false;
    });
  }

  private function getFieldsForStichwortSearch()
  {
    $possibleFields = array_keys($this->dbwKurse->getAvailableSearchFieldsStichwort());

    $excludedFields = explode(',', $this->tool4Settings->excludeKursSearchFieldsStichwort);

    return array_diff($possibleFields, $excludedFields);
  }

  private function writeSuggestionsToDb($pSuggestions)
  {
    $this->dbUtil->efficientInsertValuesIntoSingleColumnTable('web_suggestions', 'suggestion', $pSuggestions);
  }

  
  public function getSuggestions($pQuery)
  {
    $qb = $this->dbUtil->getSelectQueryBuilder();
    $qb->select('suggestion')
            ->from('web_suggestions')
            ->where('suggestion like :query:')
            ->paramString('query', $pQuery . '%');
    $sql = $qb->getSQL();

    return $this->dbUtil->getSingleColumnDbResult($sql, 'suggestion');
  }

  public function getStichwortSearchFieldsFromNotKursTableToIndex()
  {
    $fields = $this->getFieldsForStichwortSearch();
    $otherFields = array_filter($fields, function($item) {
      return strpos($item, '.') !== false;
    });
    $result = array();
    foreach ($otherFields as $f) {
      $split = explode('.', $f);
      $tableName = $split[0];
      if (!isset($result[$tableName])) {
        $result[$tableName] = array();
      }
      $result[$tableName][] = $split[1];
    }

    return $result;
  }
}