<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, 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()
  {
    foreach ($this->dataModulAry as $datamodul) {
      if ($datamodul->getVarValue($this->getValueFieldName()) == $this->selectedValue) {
        return $datamodul;
      }
    }

    return null;
  }

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

  public function getOptionen()
  {
    $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($option)
  {
    return $option->value == $this->selectedValue;
  }

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

    return $optionen;
  }

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

    return $option;
  }

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

  abstract protected function getDatamodulAry();

  abstract protected function getValueFieldName();

  abstract protected function getTextFieldName();
}

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