<?php

namespace Fifa\ConnectId\Sdk\Notifications;

use DateTime;
use Fifa\ConnectId\Sdk\ApiModelValidation\ApiModelValidator;
use Fifa\ConnectId\Sdk\ApiModelValidation\DateTimeValidatingParser;
use Fifa\ConnectId\Sdk\ApiModelValidation\FifaIdValidator;
use Fifa\ConnectId\Sdk\Exception\XmlDeserializationException;
use Fifa\ConnectId\Sdk\Registration\ValidationException;
use Fifa\ConnectId\Sdk\Util\XmlDeserializer\XmlDeserializer;
use Fifa\ConnectServiceBus\Sdk\Message\Message;
use ReflectionException;

class MessageHandlingHelper
{
    /**
     * @param Message $message
     * @param string $dtoClass
     * @param XmlDeserializer $xmlDeserializer
     * @return object
     * @throws XmlDeserializationException
     */
    public static function getDto(Message $message, string $dtoClass, XmlDeserializer $xmlDeserializer)
    {
        $xml = $message->getContent();
        if ($xml == null) {
            throw new XmlDeserializationException($xml, "Unable to deserialize message content to " . $dtoClass . ". Content is null.");
        }
        try {
            return $xmlDeserializer->deserialize($xml);
        } catch (ReflectionException $e) {
            throw new XmlDeserializationException($xml, "Unable to deserialize message content to " . $dtoClass);
        }
    }

    /**
     * @return DateTime
     * @throws ValidationException
     * @var mixed $dto
     */
    public static function validateAndParse($dto): DateTime
    {
        FifaIdValidator::validate($dto->PersonFIFAId, "PersonFIFAId");
        ApiModelValidator::cannotBeNullOrWhitespace($dto->ActorName, "ActorName");
        return DateTimeValidatingParser::parse($dto->OperationTimestamp, "OperationTimestamp");
    }
}