<?php

declare(strict_types=1);

namespace Drupal\netforum\xWeb;

use Drupal\netforum\xWeb\Generated\ServiceType\Service;

class NetForumXml extends Service {

  /**
   * XML Namespace for NetForum.
   */
  public const XML_NAMESPACE = 'http://www.avectra.com/2005/';

  /**
   * Instance of a class implementing AuthTokenHandlerInterface to use for
   * handling xWeb Authentication.
   */
  public const XWEB_AUTH_TOKEN_HANDLER = 'nf_xweb_auth_token_handler';

  /**
   * Instance of a class implementing LoggerInterface to use for handling
   * logging.
   */
  public const XWEB_LOG_HANDLER = 'nf_xweb_log_handler';

  /**
   * Setting to log all requests and responses.
   */
  public const XWEB_DEBUG_LOG_ALL = 'nf_xweb_debug_log_all';

  public function __construct(array $wsdlOptions = []) {
    parent::__construct($wsdlOptions);

    /** @var SoapClient $client */
    $client = $this->getSoapClient();
    if (isset($wsdlOptions[self::XWEB_AUTH_TOKEN_HANDLER])) {
      $client->__setTokenHandler($wsdlOptions[self::XWEB_AUTH_TOKEN_HANDLER]);
    }
    if (isset($wsdlOptions[self::XWEB_LOG_HANDLER])) {
      $client->__setLogHandler($wsdlOptions[self::XWEB_LOG_HANDLER]);
    }
    if (isset($wsdlOptions[self::XWEB_DEBUG_LOG_ALL])) {
      $client->__setLogAllRequestsResponses($wsdlOptions[self::XWEB_DEBUG_LOG_ALL]);
    }
  }

  /**
   * Returns the message from the last SoapFault. If there is no SoapFault,
   * returns null.
   */
  public function getLastErrorMessage(): ?string {
    $lastError = $this->getLastSoapFault();
    if ($lastError instanceof \SoapFault) {
      return $lastError->getMessage();
    }

    return NULL;
  }

  /**
   * Returns the last SoapFault which coincides with the last failed Soap
   * function call.
   */
  public function getLastSoapFault(): ?\SoapFault {
    $errors = $this->getLastError();
    $lastError = end($errors);

    if ($lastError instanceof \SoapFault) {
      return $lastError;
    }

    return NULL;
  }

}
