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

namespace Kufer\Web\KuferTools\Ausgaben\SammelEMail\AnDozenten;

use Kufer\Mail\Attachment\EMailAttachmentPDF;
use Kufer\Mail\EMail\IEMail;
use Kufer\Mail\Sender\IEMailSender;
use Kufer\Mail\Sender\Result\EMailSentResult;

abstract class SendSammelEMailUseCase extends \Kufer\Web\KuferTools\Ausgaben\SammelEMail\SendSammelEMailUseCase
{
  public function __construct($request, $response = null)
  {
    parent::__construct($request, $response ?? new SendSammelEMailResponse());
  }

  
  protected function getDozenten(): array
  {
    if (!empty($this->request->knr) && count($this->request->dozNummern) > 0) {
      return $this->sendPreparer->getDozenten($this->request->knr, $this->sendPreparer->getIdsFromRequest($this->request->dozNummern));
    } else {
      \Logger::logg(' Fehler im EmailSender: Kursnr. oder Dozentennummern nicht besetzt. ', 41);

      throw new \Exception('Es wurde kein Dozent ausgewaehlt.');
    }
  }

  protected function getAttachments(): array
  {
    $result = parent::getAttachments();
    if ($this->isTnListAnhang()) {
      $content = \KontaktUserAPI::getContent4PDFList($this->kurs->id, $this->getToolId());
      $result[] = new EMailAttachmentPDF('PDF Liste.pdf', $content);
    }

    return $result;
  }

  
  protected function isTnListAnhang(): bool
  {
    return $this->request->anhangTnList;
  }

  protected function setEmailStatusReponseFromDozentenResult(EMailSentResult $result): void
  {
    foreach ($result->getRecipients() as $recipient) {
      $doz = $recipient->getRecipient();
      $this->response->sendMailStatus[$doz->id] = $recipient->isError() ? self::EMAILVERSAND_FEHLER_BEIM_VERSENDEN : self::EMAILVERSAND_SUCCESS;
    }
  }

  
  abstract protected function getSenderPosition(): string;

  abstract protected function getSenderPerson(): \Personn;

  protected function sendEMail(IEMailSender $sender, IEMail $mail): EMailSentResult
  {
    $result = parent::sendEMail($sender, $mail);
    $dozenten = $this->getDozenten();
    $this->response->dozenten = $dozenten;
    $resultDozentenEmail = \call_user_func(array($sender, 'sendFrom' . $this->getSenderPosition() . 'ToDozent'), $mail, $this->getSenderPerson(), $dozenten);
    $this->setEmailStatusReponseFromDozentenResult($resultDozentenEmail);
    $result = $result->merge($resultDozentenEmail);

    if ($this->shouldSaveEMailAnDozentInDokumentenverwaltung()) {
      $this->response->saveDozenten = true;
      $documentManagerBuilder = new \Kufer\Web\KuferTools\Utils\Builder\EMailDokumentenverwaltungBuilder($mail->getSubject(), $mail->getContent(), $mail->getContentType() == \Kufer\Mail\EMail\IEMail::TYPE_HTML);
      $documentManagerBuilder
        ->addKontakte((new \Kufer\Web\Classes\Stream\ArrayStream($resultDozentenEmail->getSuccess()))
          ->merge(new \Kufer\Web\Classes\Stream\ArrayStream($resultDozentenEmail->getWarnings()))
          ->map(static function(\Kufer\Mail\Sender\Result\EMailSentRecipient $recipient) {
            return $recipient->getRecipient();
          })->toArray())
        ->setKurs($this->kurs->id)
        ->setInfo('Aus den KuferTools versendet')
        ->setVersandtVomCurrentMitarbeiter()
        ->commit();

      $documentManagerBuilder = new \Kufer\Web\KuferTools\Utils\Builder\EMailDokumentenverwaltungBuilder('Nicht versendet: ' . $mail->getSubject(), $mail->getContent(), $mail->getContentType() == \Kufer\Mail\EMail\IEMail::TYPE_HTML);
      $documentManagerBuilder
        ->addKontakte(\array_map(function(\Kufer\Mail\Sender\Result\EMailSentRecipient $recipient) {
          return $recipient->getRecipient();
        }, $resultDozentenEmail->getErrors()))
        ->setKurs($this->kurs->id)
        ->setInfo('Fehlerhafter Versandt aus den KuferTools')
        ->setVersandtVomCurrentMitarbeiter()
        ->commit();
    }

    return $result;
  }

  protected function shouldSaveEMailAnDozentInDokumentenverwaltung(): bool
  {
    return false;
  }
}