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

namespace Kufer\KuferTools\Utils\WssField;

class WssFieldKursplanungKooperationspartner extends WssField
{
  protected function getFieldBearbeitbar($datamodulWert, $isFormular, string $requestPrefix = '')
  {
    return $this->_buildField($this->datamodulColumn, $datamodulWert, 2, false);
  }

  protected function getFieldNichtBearbeitbar($datamodulWert, $isFormular, string $requestPrefix = '')
  {
    if ($isFormular) {
      return $this->_buildField($this->datamodulColumn, $datamodulWert, 1, false);
    } else {
      return parent::getFieldNichtBearbeitbar($datamodulWert, $isFormular, $requestPrefix);
    }
  }

  protected function isMandatoryValueEmpty($value)
  {
    return count($value) === 0;
  }

  protected function getValue($datamodulWert, $isFormular = false)
  {
    if (is_array($datamodulWert->dozenten) && count($datamodulWert->dozenten) > 0) {
      $dozenten = array_values(array_filter($datamodulWert->dozenten, function($doz) {return $doz->typ == 'I';}));
      if (count($dozenten) > 0) {
        $dozZeilen = array();
        foreach ($dozenten as $dozent) {
          
          $dozZeilen[] = '<span>' . $dozent->getVarValue('titel_name_vorname') . '</span>';
        }

        return implode('<br>', $dozZeilen);
      }
    }

    return 'keine Kooperationspartner angegeben';
  }

  protected function encodeValue($value)
  {
    
    return $this->dontEncode($value);
  }

  public function inPost(string $requestPrefix = ''): bool
  {
    return \PostOperations::isDefined(($requestPrefix === '' ? '' : $requestPrefix . '_') . 'kursplanung_kooperationspartner_hidden');
  }

  private function getDozKomEintrag($kommArt, $kommWert, $kommBezeichner)
  {
    $komm = new \KursplanungDozentenKomm();
    $komm->art = $kommArt;
    $komm->wert = $kommWert;
    $komm->bezeichner = $kommBezeichner;

    return $komm;
  }

  private function getDozKommunikation($dozentPost)
  {
    $kommunikation = array();

    if (trim($dozentPost->emailPrivat) != '') {
      $kommunikation[] = $this->getDozKomEintrag('E', $dozentPost->emailPrivat, 'E-Mail privat');
    }

    if (trim($dozentPost->emailDienstlich) != '') {
      $kommunikation[] = $this->getDozKomEintrag('E', $dozentPost->emailDienstlich, 'E-Mail dienstlich');
    }

    if (trim($dozentPost->festnetzPrivat) != '') {
      $kommunikation[] = $this->getDozKomEintrag('T', $dozentPost->festnetzPrivat, 'Telefon privat');
    }

    if (trim($dozentPost->festnetzDienstlich) != '') {
      $kommunikation[] = $this->getDozKomEintrag('T', $dozentPost->festnetzDienstlich, 'Telefon dienstlich');
    }

    if (trim($dozentPost->weblink) != '') {
      $kommunikation[] = $this->getDozKomEintrag('W', $dozentPost->weblink, 'Homepage');
    }

    if (trim($dozentPost->mobilPrivat) != '') {
      $kommunikation[] = $this->getDozKomEintrag('M', $dozentPost->mobilPrivat, 'Mobil privat');
    }

    if (trim($dozentPost->mobilDienstlich) != '') {
      $kommunikation[] = $this->getDozKomEintrag('M', $dozentPost->mobilDienstlich, 'Mobil dienstlich');
    }


    return $kommunikation;
  }

  public function getValueFromPost(string $requestPrefix = '')
  {
    $jsonBase64 = \PostOperations::getVarValue(($requestPrefix === '' ? '' : $requestPrefix . '_') . 'kursplanung_kooperationspartner_hidden');
    $dozenten = \JsonOperations::getFromStringBase64InternalEncoding($jsonBase64);

    $dozAry = array();
    foreach ($dozenten as $dozent) {
      $doz = new \KursplanungDozenten();

      $doz->typ = 'I';
      $doz->nr = $dozent->id;

      $doz->name = \StringOperations::substr($dozent->name, 0, \DBWorkDozenten::FIELD_NAME_MAX_LENGTH);
      $doz->vorname = \StringOperations::substr($dozent->vorname, 0, \DBWorkDozenten::FIELD_VORNAME_MAX_LENGTH);
      $doz->name_titel = $dozent->anredetitel;
      $doz->ort = $dozent->plz . ' ' . $dozent->ort;
      $doz->strasse = $dozent->strasse;
      $doz->gemeinde = $dozent->gemeinde;
      $doz->stadtteil = $dozent->stadtteil;
      $doz->bezirk = $dozent->bezirk;
      $doz->bundesland = $dozent->bundesland;
      $doz->kommunikation = $this->getDozKommunikation($dozent);
      $dozAry[] = $doz;
    }

    return $dozAry;
  }

  public function getChangedInfo($columnValues, $changedDm, $changedFields): array
  {
    $datamodul = $this->datamodulColumn->datamodul;
    $fieldname = $this->datamodulColumn->fieldname;
    if (isset($columnValues[$datamodul][$fieldname])) {
      $newData = $columnValues[$datamodul][$fieldname];
      if (!is_array($changedDm->dozenten)) {
        $changedDm->dozenten = array();
      } else {
        
        $changedDm->dozenten = array_filter($changedDm->dozenten, function($doz) {
          return $doz->typ != 'I';
        });
      }
      
      $changedDm->dozenten = array_merge($changedDm->dozenten, $newData);
      $changedFields[] = 'dozentenauswahl'; 
    }

    return array('changed' => $changedDm, 'changedFields' => $changedFields);
  }

  private function _buildField($field, $datamodulWert, $privileg, $pPrintversion)
  {
    $canedit = ($privileg == 2 && !$pPrintversion && $field->canedit);

    $htmlField = $this->_getArea($datamodulWert, $pPrintversion, $field, $canedit);
    if ($canedit) {
      $htmlField .= '<div class="koop_buttons" style="position: absolute; right: 25px; top: 5px; font-size: 2em;">';

      $htmlField
        .= '<div style="resize: none;">'
          . '<span class="button_new_koop_test" title="Kooperationspartner auswählen">'
            . '<i class="fa fa-address-book-o"></i>'
          . '</span>'
        . '</div>';

      $htmlField
        .= '<div style="resize: none;">'
          . '<span class="button_new_koop" title="Neuer Kooperationspartner">'
            . '<i class="fa fa-user-plus"></i>'
          . '</span>'
        . '</div>';

      $htmlField
        .= '<div style="resize: none;">'
          . '<span class="button_update_koop" title="Kooperationspartner ändern">'
            . '<i class="fa fa-edit"></i>'
          . '</span>'
        . '</div>';

      $htmlField
        .= '<div style="resize: none;">'
          . '<span class="button_delete_koop" title="Kooperationspartner entfernen">'
            . '<i class="fa fa-trash"></i>'
          . '</span>'
        . '</div>';

      $htmlField .= '</div>';
    }

    if (!$pPrintversion) {
      
      static $callInit = true;
      if ($callInit) {
        $htmlField .= $this->initJS();
        $callInit = false;
      }
    }

    return $htmlField;
  }

  private function initJS()
  {
    return '';
  }

  private function _getArea($datamodulWert, $pPrintversion, $field, $pEditable)
  {
    $fieldname = $this->_getFieldname($field);

    $dozenten = array_values(array_filter($datamodulWert->dozenten, function($doz) {return $doz->typ == 'I';}));

    $dozentenJs = array_map(function($dozent) {
      $doz = new \stdClass();

      $doz->typ = 'I';
      $doz->id = $dozent->nr;

      $doz->name = $dozent->name;
      $doz->vorname = $dozent->vorname;
      $doz->plz = $dozent->getVarValue('nurplz');
      $doz->ort = $dozent->getVarValue('nurort');
      $doz->strasse = $dozent->strasse;

      $doz->gemeinde = $dozent->getVarValue('gemeinde');
      $doz->stadtteil = $dozent->getVarValue('stadtteil');
      $doz->bezirk = $dozent->getVarValue('bezirk');
      $doz->bundesland = $dozent->getVarValue('bundesland');

      $doz->emailPrivat = $dozent->getVarValue('email');
      $doz->emailDienstlich = $dozent->getVarValue('email2');
      $doz->festnetzPrivat = $dozent->getVarValue('tel');
      $doz->festnetzDienstlich = $dozent->getVarValue('tel2');
      $doz->mobilPrivat = $dozent->getVarValue('mobil');
      $doz->mobilDienstlich = $dozent->getVarValue('mobil2');
      $doz->weblink = $dozent->getVarValue('weblink');
      $doz->anredetitel = $dozent->getVarValue('name_titel');

      return $doz;
    }, $dozenten);

    $tablespaceproperties = ($pPrintversion) ? 'cellpadding="2" cellspacing="2"' : '';

    $readonly = (!$pEditable) ? 'read_only' : '';

    $pflichtfeldClass = '';
    if (!$readonly && $field->mandatory_field) {
      $pflichtfeldClass = 'form_mandatory';
    }

    $str = '<div id="' . $fieldname . '" class="recht_' . $field->privileg_key . ' ' . $fieldname . ' ' . $readonly . ' ' . $pflichtfeldClass . ' form-control mnlist" style="min-height: 177px; overflow: auto;">' . "\n"
              . '<table class="mnlisttable" border="1" ' . $tablespaceproperties . ' rules="all" style="font-size:12px; width: 95%;">' . "\n"
                . '<thead></thead>' . "\n"
                . '<tbody>' . "\n";
    $str .= '</tbody>' . "\n"
           . '</table>' . "\n"
           . '<input id="' . $fieldname . '_hidden" class="mnlist_hidden" name="' . $fieldname . '_hidden" type="hidden" value="' . \JsonOperations::encodeBase64($dozentenJs) . '">' . "\n"
            . $this->getAnredetitelDialog()
            . $this->getGemeindenDialog()
        . '</div>' . "\n";

    return $str;
  }

  private function getAnredetitelDialog()
  {
    $hlverhtext = \HLDispatcher::GetHinterlegungDialog(\HLDispatcher::HL_ANREDETITEL_DIALOG);
    $hlverhtext->fields = array('koop_anredetitel');

    return $hlverhtext->CreateDialog('hlanredetitel_div', '.hl_anredetitel_koop', 'Anredetitel');
  }

  private function getGemeindenDialog()
  {
    $hlverhtext = \HLDispatcher::GetHinterlegungDialog(\HLDispatcher::HL_GEMEINDEN_DIALOG);
    $hlverhtext->fields = array('koop_gemeinde', 'koop_bezirk', 'koop_stadtteil', 'koop_bundesland', 'koop_plz', 'koop_ort');

    return $hlverhtext->CreateDialog('hlgemeinden_div', '.hl_gemeinden_koop', 'Gemeinden');
  }
}