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

namespace Kufer\Web\Classes\Api\SearchRestriction;


interface ISearchInfoExtractor
{
  public function setIdField($pName);

  public function getIdField();

  public function setInterestingFields($pArray);

  public function getInterestingFields();

  public function getAllIds();

  public function addId($pId);

  public function addInfo($pKey, $pValue);

  public function getInfo($pKey);
}

class SearchInfoExtractor implements ISearchInfoExtractor
{
  private $idField;
  private $foundIds = array();
  private $interestingFields = array();
  private $aggregatedValues = array();

  public function setIdField($pName)
  {
    $this->idField = $pName;
  }

  public function getIdField()
  {
    return $this->idField;
  }

  public function setInterestingFields($pArray)
  {
    $this->interestingFields = $pArray;
  }

  public function getInterestingFields()
  {
    return $this->interestingFields;
  }

  public function addId($pId)
  {
    $this->foundIds[] = $pId;
  }

  public function getAllIds()
  {
    return $this->foundIds;
  }

  public function addInfo($pKey, $pValue)
  {
    if (!isset($this->aggregatedValues[$pKey])) {
      $this->aggregatedValues[$pKey] = array();
    }
    if (!isset($this->aggregatedValues[$pKey][$pValue])) {
      $this->aggregatedValues[$pKey][$pValue] = 0;
    }
    $this->aggregatedValues[$pKey][$pValue]++;
  }

  public function getInfo($pKey)
  {
    if (isset($this->aggregatedValues[$pKey])) {
      return $this->aggregatedValues[$pKey];
    } else {
      return array();
    }
  }

  public function extractOrtPlzInfo()
  {
    return $this->getOrtInfo(function($ort) {
      return \StringOperations::getPLZ($ort->ort);
    });
  }

  private function getOrtInfo($extractFunction)
  {
    $orte = $this->getInfo('ort');
    $result = array();
    $raumNamen = array_keys($orte);
    $kursorte = \DBWorkKursorteWB::getDefaultInstance()->getKursorteByMktextary($raumNamen);
    foreach ($kursorte as $ort) {
      if (isset($orte[$ort->mktext])) {
        $val = $extractFunction($ort);
        if (!isset($result[$val])) {
          $result[$val] = 0;
        }
        $result[$val] += $orte[$ort->mktext];
      }
    }

    return $result;
  }

  public function extractOrtStadtInfo()
  {
    return $this->getOrtInfo(function($ort) {
      return \StringOperations::getOrt($ort->ort);
    });
  }
}