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

namespace Kufer\Web\KuferTools\Allgemein\VhsNachricht;

use Kufer\Web\KuferTools\Utils\StatusMessages\PlainStatusMessage;
use Kufer\Web\KuferTools\Utils\StatusMessages\StatusMessageContainer;

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

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

    return true;
  }

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

  public static function getToolSectionId()
  {
    return 315;
  }

  public function action()
  {
    $user = $this->getUser();
    if (!$this->request->isRefresh) {
      $smc = StatusMessageContainer::getSharedInstance();
      foreach ($this->request->uploadFiles as $uploadFile) {
        if ($uploadFile->errorType !== UPLOAD_ERR_OK) {
          $smc->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(strip_tags($uploadFile->errorMsg)));
        }
      }

      $emailStatus = \Kufer\Web\KuferTools\Utils\SendFeedback::sendGeneralFeedback(
        $this->getToolId(),
        $this->getToolSectionId(),
        $this->session->getCurrentWebToolsPerson(),
        $user,
        $this->request->nachricht_betreff,
        $this->request->nachricht_body,
        $this->request->uploadFiles,
        $this->toolSettings->copyToSenderUser
      );
    } else {
      $emailStatus = (new \Kufer\Mail\Sender\Result\EMailSentResult(array()))->toReadableMessages();
    }

    return $this->getResponse($emailStatus, $user);
  }

  protected function getResponse($emailStatus, $pUser)
  {
    $this->handleResponseStrategies();
    $this->response->emailStatus = $emailStatus;
    $this->response->user = $pUser;
    $this->response->isRefresh = $this->request->isRefresh;

    return $this->response;
  }

  protected function getResponseStrategies()
  {
    return array(
        new \Kufer\Web\KuferTools\Utils\ResponseStrategies\ResponseMitRahmen($this)
    );
  }
}

class SendVhsNachrichtRequest
{
  public $nachricht_betreff;
  public $nachricht_body;
  public $uploadFiles;
  public $isRefresh;
  public $isXsrfOk;
}

class SendVhsNachrichtResponse extends \Kufer\Web\KuferTools\Basis\UseCase\ToolResponse
{
  public $menuPunkte;
  public $user;
  public $emailStatus;
  public $isRefresh;
  public $action;
}