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

namespace Kufer\Web\KuferTools\Utils\KursHandler;

use Kufer\Web\KuferTools\Basis\BenachrichtigungNachBearbeiten\BenachrichtigungUtils;
use Kufer\Web\KuferTools\Utils\StatusMessages\PlainStatusMessage;

class KursUpdaterWss extends KursUpdater
{
  protected $wssHandler;
  protected $columnValues;

  
  public function __construct($pKnr, \ToolSettings $toolSettings, $pToolId, $pToolSectionId, $pWssHandler, $pColumnValues)
  {
    parent::__construct($pKnr, $toolSettings, $pToolId, $pToolSectionId);
    $this->wssHandler = $pWssHandler;
    $this->columnValues = $pColumnValues;
  }

  public function doUpdate($pUser): bool
  {
    if ($this->validateFields()) {
      return parent::doUpdate($pUser);
    } else {
      \Logger::logg('Bearbeiten eines Kurses: - Validierung fehlgeschlagen', 200);
      $this->setStatusMessageFailureValidationContent($this->getWrongFields());

      return false;
    }
  }

  protected function validateFields()
  {
    $wrongFields = $this->getWrongFields();

    return count($wrongFields) == 0;
  }

  protected function setStatusMessageFailureValidationContent($pWrongFields)
  {
    $message = \Kufer\Web\KuferTools\Utils\WssHandler::getErrorMessage($pWrongFields);
    $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($message));
  }

  protected function getWrongFields()
  {
    static $cache = null;
    if (is_null($cache)) {
      $cache = $this->wssHandler->checkColumnValues($this->toolSettings, $this->columnValues);
    }

    return $cache;
  }

  protected function getChangedKurs()
  {
    $origKurs = $this->getOrigKurs();
    $changedKurs = $this->wssHandler->getChangedDm(
      $this->toolSettings,
      $origKurs,
      $this->columnValues
    );

    if (\DBWorkBASysSettings::isSalzburgBildungswerk()) {
      $changedKurs->abschluss = 'Y';
    }

    return $changedKurs;
  }

  protected function getChangedFields()
  {
    $origKurs = $this->getOrigKurs();
    $changedFields = $this->wssHandler->getChangedFieldnames(
      $this->toolSettings,
      $origKurs,
      $this->columnValues
    );

    if (\DBWorkBASysSettings::isSalzburgBildungswerk()) {
      $changedFields[] = 'abschluss';
    }

    return $changedFields;
  }

  
  protected function sendeBenachrichtigung($pOrigKurs, $pChangedKurs, $pChangedFields, $pUser)
  {
    $changedFieldsLabels = $this->wssHandler->getFieldsInReadableFormat($pChangedFields);
    $footerText = 'Kurs Bearbeiten';

    $columns = $this->wssHandler->getColumnsCached();
    BenachrichtigungUtils::sendeBenachrichtigungEmailKursdaten(
      $columns,
      $pOrigKurs,
      $pChangedKurs,
      $pChangedFields,
      $changedFieldsLabels,
      $footerText,
      $pUser,
      $this->toolSettings,
      $this->toolId,
      $this->toolSectionId
    );
  }
}