<?php

namespace Fifa\ConnectId\Sdk\Registration;

use Fifa\ConnectId\Sdk\Util\Serialization\XmlSerializerInterface;
use InvalidArgumentException;

class DeserializingCorrelationIdBasedItemProvider implements CorrelationIdBasedItemProviderInterface
{
    /**
     * @var CorrelationIdBasedItemProviderInterface
     */
    private $serializedItemProvider;

    /**
     * @var XmlSerializerInterface
     */
    private $serializer;

    public function __construct(CorrelationIdBasedItemProviderInterface $messageReceivedProvider, XmlSerializerInterface $serializer)
    {
        $this->serializedItemProvider = $messageReceivedProvider;
        $this->serializer = $serializer;
    }

    /**
     * Method retrieves MessageReceived from cache and deserializes it
     *
     * @return object|null - deserialized message received
     */
    public function getByCorrelationId(string $correlationId)
    {
        $item = $this->serializedItemProvider->getByCorrelationId($correlationId);
        if ($item == null) {
            return null;
        }

        if (!($item instanceof MessageReceived)) {
            throw new InvalidArgumentException(sprintf('Item should be of type MessageReceived, but was %s', get_class($item)));
        }

        return $this->serializer->deserialize($item->getXmlData());
    }
}