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

namespace Kufer\KuferTools\Ausgaben\SammelEMail;

use Kufer\KuferTools\Ausgaben\CommonTasks\SendPrepare as SendPrepare;
use Kufer\KuferTools\Ausgaben\SammelEMail\EmailTasks\MailAnAbsenderCommand as MailAnAbsenderCommand;
use Kufer\KuferTools\Ausgaben\SammelEMail\EmailTasks\MailAnEinrichtungCommand as MailAnEinrichtungCommand;
use Kufer\KuferTools\Ausgaben\SammelEMail\EmailTasks\MailAnEmpfaengerCommand as MailAnEmpfaengerCommand;
use Kufer\KuferTools\Ausgaben\SammelEMail\EmailTasks\MailAnPlanendenMitarbeiterCommand as MailAnPlanendenMitarbeiterCommand;
use Kufer\KuferTools\Ausgaben\SammelEMail\EmailTasks\MailAnVerwaltendenMitarbeiterCommand as MailAnVerwaltendenMitarbeiterCommand;

abstract class SendEMailUseCase extends \Kufer\KuferTools\Basis\UseCase\ToolUseCase
{
  const EMAILVERSAND_SUCCESS = SendSammelEMailUseCase::EMAILVERSAND_SUCCESS;
  const EMAILVERSAND_FEHLER_BEIM_VERSENDEN = SendSammelEMailUseCase::EMAILVERSAND_FEHLER_BEIM_VERSENDEN;
  const EMAILVERSAND_UNGUELTIGE_ODER_LEERE_EMAIL = SendSammelEMailUseCase::EMAILVERSAND_UNGUELTIGE_ODER_LEERE_EMAIL;
  const EMAILVERSAND_STANDBY = SendSammelEMailUseCase::EMAILVERSAND_STANDBY;

  
  protected $emailSender;
  
  
  protected $sendPreparer;
  
  public function __construct($request, $response = null)
  {
    parent::__construct($request, $response ?? new SendEMailResponse());
    $this->sendPreparer = new SendPrepare();
    $this->emailSender = $this->getEmailSender();
  }

  
  
  protected abstract function getEmailSender();

  public function action() {
    $errorMessage = '';
    $this->kontaktUser = array();
    try {
      
      if  ($this->emailSender->isUploadFault()) {
        $this->response->uploadFailed = true;
      }
      
      elseif($this->request->isRefresh) {
        $this->response->doppeltSenden = true;
      }
      
      else {
        
        $this->sendSammelEMail();
      } 
    } 
    catch (\Exception $e ) {
      $errorMessage = $e->getMessage();
      \Logger::logg('Fehler beim Versenden der Sammel E-Mail. '.$errorMessage, 41);
    }
    
    return $this->getResponse($errorMessage);
  } 

  public function hasAccess($pToolSectionId = NULL)
  {
    
    
    if(!parent::hasAccess()) {
      return false;
    }
    
    
    if(!$this->request->isXsrfOk && !$this->request->isRefresh) {
      return false;
    }
    return true;
  } 
  
  
  protected function getResponse($pErrorMessage = '')
  {
    $this->handleResponseStrategies();
    $this->response->errorMessage = $pErrorMessage;
    return $this->response;
  }
  
  protected function getResponseStrategies()
  {
    return array(
        new \Kufer\KuferTools\Utils\ResponseStrategies\ResponseMitRahmen($this)
    );
  }
  
  
  protected function sendSammelEMail()
  {
    $subCommandAry = array();
    $subCommandAry = $this->addAdditionalCommands($subCommandAry);
    $this->emailSender->addCommands($subCommandAry);
    $this->versendeMails();
  }
  
  public function getEmpfaengerDescription($empfaenger): string
  {
    return $this->response->{$empfaenger.'Name'};
  }
  
  
  protected function addAdditionalCommands(array $subCommandAry): array
  {
    return $subCommandAry;
  }
  
  
  protected function versendeMails() 
  {
    
    
    $emailContent = array();
    $emailContent['betreff'] = $this->request->emailBetreff;
    $emailContent['body'] = $this->request->emailBody;
    $emailContent['isHtml'] = isset($this->request->isHtml) && $this->request->isHtml;
    $toolid = $this->getToolId();
    
    
    
    $attachStrategy = $this->emailSender->getAttachStrategy($toolid, $this->isTnListAnhang());
    
    
    
   
    
    
    $versandStatus = $this->emailSender->sendMail2User($this->kontaktUser, $this->getUser(), $toolid, $this->getToolSectionId(), null, 
                                                    $emailContent, $attachStrategy);
    
    $additionalEmpfaengerArray = $this->getAddiationEmpfaengerArray();

    foreach ($additionalEmpfaengerArray as $empfaenger) {
      $this->setAdditionalStatusResponse($versandStatus->$empfaenger, $empfaenger);
    }
    
    $this->setAdditionalStatusResponses($versandStatus);
    
    
    $this->emailSender->deleteAnhangFiles();
  } 
  
  protected function getAddiationEmpfaengerArray()
  {
    return \array_filter(\array_reduce(\array_map('\array_keys', $this->emailSender->getCommands()),
        function ($ary0, $ary1) {
          return \array_merge($ary0, $ary1);
        }, array()), array($this, 'filterFromAddiationEmpfaengerArray'));;
  }
  
  protected function filterFromAddiationEmpfaengerArray(string $str): bool {
    return true;
  }
  
  protected function setAdditionalStatusResponses($versandStatus)
  {
  }

  
  protected function setAdditionalStatusResponse($pAbsender, $pEmpfaenger) {
    if (isset($pAbsender['versendet']) && count($pAbsender['versendet']) != 0) {
      foreach ($pAbsender['versendet'] as $absKey => $absObj) { 
        $this->response->{$pEmpfaenger.'Name'} = $this->getAbsenderName($absObj, $pEmpfaenger);
        $this->response->{$pEmpfaenger.'MailStatus'} = self::EMAILVERSAND_SUCCESS;
      }
    }
    if (isset($pAbsender['nichtVersendet']) && count($pAbsender['nichtVersendet']) != 0) {
      foreach ($pAbsender['nichtVersendet'] as $absKey => $absObj) {
        $this->response->{$pEmpfaenger.'Name'} = $this->getAbsenderName($absObj, $pEmpfaenger);
        $this->response->{$pEmpfaenger.'MailStatus'} = self::EMAILVERSAND_FEHLER_BEIM_VERSENDEN;
      }
    }
    return  $pAbsender;
  }
  
  protected function getAbsenderName($absObj, $pEmpfaenger)
  {
    if (\is_null($absObj)) {
      return $pEmpfaenger;
    }
    if (\is_string($absObj)) {
      return $absObj;
    }
    
    return $absObj->namevorname ?? $absObj->getVarValue('namevorname');
  }
  
  protected function isTnListAnhang(): bool
  {
    return false;
  }
}

class SendEMailRequest
{
  public $emailBetreff;
  public $emailBody;
  public $emailIsHtml;
  public $isRefresh;
  public $isXsrfOk;
}

class SendEMailResponse extends \Kufer\KuferTools\Basis\UseCase\ToolResponse
{
  public $kurs;
  public $user;
  public $menuBar;
  public $errorMessage;
  public $sendMailStatus = array();
  public $uploadFailed = false;
  public $doppeltSenden = false;
}