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

namespace Kufer\KuferTools\Allgemein\VhsNachricht;

use Kufer\KuferTools\Utils\StatusMessages\StatusMessage;
use Kufer\KuferTools\Utils\StatusMessages\StatusMessageContainer;

class SendVhsNachrichtUseCase extends \Kufer\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(StatusMessage::getErrorMessageObj(strip_tags($uploadFile->errorMsg)));
        }
      }

      $emailStatus = \Kufer\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\KuferTools\Utils\ResponseStrategies\ResponseMitRahmen($this)
    );
  }
}

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

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