<?php


namespace Fifa\ConnectId\Sdk\Notifications;

use Fifa\ConnectId\Sdk\MessageHandlers\MessageHandlerInterface;
use Fifa\ConnectId\Sdk\MessageHandlers\MessageHandlersUtil;
use Fifa\ConnectId\Sdk\Util\Data\Message\ActionType;
use Fifa\ConnectId\Sdk\Util\XmlDeserializer\XmlDeserializer;
use Fifa\ConnectServiceBus\Sdk\Message\Message;

class PersonNameChangedMessageHandler implements MessageHandlerInterface
{
    /**
     * @var PersonNameChangedNotificationHandlerInterface
     */
    private $personNameChangedNotificationHandler;
    /**
     * @var XmlDeserializer
     */
    private $xmlDeserializer;

    public function __construct(PersonNameChangedNotificationHandlerInterface $personNameChangedNotificationHandler)
    {
        $this->personNameChangedNotificationHandler = $personNameChangedNotificationHandler;
        $this->xmlDeserializer = new XmlDeserializer(PersonNameChangedNotificationDto::class, []);
    }

    /**
     * @inheritDoc
     */
    public function canHandle(?string $messageType): bool
    {
        return $messageType == ActionType::PERSON_NAME_CHANGED_NOTIFICATION;
    }

    /**
     * @inheritDoc
     */
    public function handle(?string $messageType, Message $message)
    {
        /** @var PersonNameChangedNotificationDto $dto */
        $dto = MessageHandlingHelper::getDto($message, PersonNameChangedNotificationDto::class, $this->xmlDeserializer);
        $operationTimestamp = MessageHandlingHelper::validateAndParse($dto);

        $notificationData = new PersonNameChangedNotification($dto->PersonFIFAId, $dto->ActorName, $operationTimestamp);
        $this->personNameChangedNotificationHandler->execute($notificationData);
    }

    /**
     * String representation of the object
     */
    public function __toString()
    {
        return MessageHandlersUtil::FullNameWithMessageType($this, ActionType::PERSON_NAME_CHANGED_NOTIFICATION);
    }
}