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

namespace Kufer\Web\KuferTools\Veranstalter\KursUebersicht\KursDetails\KursBearbeiten;

use Kufer\Web\KuferTools\Utils\KursHandler\KursUpdaterWss;

class KursBearbeitenAbsendenUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\ToolUseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new KursBearbeitenAbsendenResponse());
  }

  public static function getToolId()
  {
    return \ToolsAPI::TOOL_KURSUEBERSICHT_VA;
  }

  protected function getKursHelper()
  {
    return \Kufer\Web\KuferTools\Utils\DatamodulHelper\Kurse\KursHelperFactory::getKursHelperByToolID($this->getToolId(), $this->toolSettings);
  }

  public function getAllKursnrOhneFilter()
  {
    $kurshelper = $this->getKursHelper();

    return $kurshelper->getIdsOhneFilter();
  }

  public function getKurs($knr)
  {
    $dbwKurse = new \DBWorkKurseWT(1, true);

    return $dbwKurse->getKurs($knr);
  }

  public static function getToolSectionId()
  {
    return 621;
  }

  public function hasAccess($pToolSectionId = null)
  {
    if (!parent::hasAccess()) {
      return false;
    }
    if (!$this->isRechtAllowed('632.0.4')) {
      return false;
    }
    if (!$this->request->isXsrfOk && !$this->request->isRefresh) {
      return false;
    }
    $alleKursnummern = $this->getAllKursnrOhneFilter();

    return in_array($this->request->knr, $alleKursnummern);
  }

  public function action()
  {
    $user = static::getUser();

    $kursUpdateHandler = new KursUpdaterWss(
      $this->request->knr,
      $this->toolSettings,
      $this->getToolId(),
      $this->getToolSectionId(),
      $this->request->wssHandler,
      $this->request->columnValues
    );
    $statusMessageContainer = null;

    if (!$this->request->isRefresh) {
      $kursUpdateHandler->doUpdate($user);
      $statusMessageContainer = $kursUpdateHandler->getStatusMessageContainer();
    }

    return $this->getResponse($statusMessageContainer);
  }

  protected function getResponse($pStatusMessageContainer)
  {
    $this->handleResponseStrategies();
    $this->response->knr = $this->request->knr;
    $this->response->statusMessageContainer = $pStatusMessageContainer;

    return $this->response;
  }
}

class KursBearbeitenAbsendenRequest
{
  public $isRefresh;
  public $isXsrfOk;
  public $knr;
  public $columnValues;
  public $wssHandler;
}

class KursBearbeitenAbsendenResponse extends \Kufer\Web\KuferTools\Basis\UseCase\ToolResponse
{
  public $knr;
  public $statusMessageContainer;
}