<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

abstract class Combobox
{
  protected $selectedValue;
  protected $dataModulAry = array();

  protected $dataModul;

  public function __construct($pSelectedValue = null, $pDataModul = null)
  {
    $this->selectedValue = $pSelectedValue;
    
    $this->dataModul = $pDataModul;
    
    $this->dataModulAry = $this->getDatamodulAry();
  }

  public function getSelectedDatamodul(): ?\Datamodul
  {
    foreach ($this->dataModulAry as $datamodul) {
      if ($datamodul->getVarValue($this->getValueFieldName()) == $this->selectedValue) {
        return $datamodul;
      }
    }

    return null;
  }

  public function getSelectedText(): string
  {
    $datamodul = $this->getSelectedDatamodul();
    if (!is_null($datamodul)) {
      return $this->getText($datamodul);
    } else {
      return '';
    }
  }

  
  public function getOptionen(): array
  {
    $optionen = array();
    foreach ($this->dataModulAry as $datamodul) {
      $option = new \ComboboxOption();
      $option->value = $datamodul->getVarValue($this->getValueFieldName());

      $option->text = $this->getText($datamodul);
      $option->isSelected = $this->isSelected($option);
      $optionen[] = $option;
    }

    return $optionen;
  }

  protected function isSelected(\ComboboxOption $option): bool
  {
    return $option->value == $this->selectedValue;
  }

  
  public function getOptionenMitDefaultOption(): array
  {
    $defaultOption = $this->getDefaultOption();
    $optionen = $this->getOptionen();
    if (!is_null($defaultOption)) {
      array_unshift($optionen, $defaultOption);
    }

    return $optionen;
  }

  protected function getDefaultOption(): ?\ComboboxOption
  {
    $option = new \ComboboxOption();
    $option->value = '';
    $option->text = '';
    $option->isSelected = is_null($this->selectedValue);

    return $option;
  }

  protected function getText($datamodul): string
  {
    return $datamodul->getVarValue($this->getTextFieldName());
  }

  abstract protected function getDatamodulAry(): array;

  abstract protected function getValueFieldName(): string;

  abstract protected function getTextFieldName(): string;
}

class ComboboxOption extends \Datamodul
{
  public $value;
  public $text;
  public $isSelected = false;
}