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

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

use Kufer\KuferTools\Utils\KursHandler\KursUpdaterWss;

class KursBearbeitenAbsendenUseCase extends \Kufer\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\KuferTools\Utils\DatamodulHelper\KursHelper\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->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\KuferTools\Basis\UseCase\ToolResponse
{
  public $knr;
  public $statusMessageContainer;
}