<?php


namespace Fifa\ConnectId\Sdk\Notifications;

use Fifa\ConnectId\Sdk\ApiModelValidation\FifaIdValidator;
use Fifa\ConnectId\Sdk\ApiModelValidation\DateTimeValidatingParser;
use Fifa\ConnectId\Sdk\MessageHandlers\MessageHandlerInterface;
use Fifa\ConnectId\Sdk\MessageHandlers\MessageHandlersUtil;
use Fifa\ConnectId\Sdk\Registration\ValidationException;
use Fifa\ConnectId\Sdk\Util\Data\Message\ActionType;
use Fifa\ConnectId\Sdk\Util\XmlDeserializer\XmlDeserializer;
use Fifa\ConnectServiceBus\Sdk\Message\Message;
use Fifa\ConnectId\Sdk\ApiModelValidation\ApiModelValidator;

class PersonMergedMessageHandler implements MessageHandlerInterface
{
    /**
     * @var PersonMergedNotificationHandlerInterface
     */
    private $personMergedNotificationHandler;
    /**
     * @var XmlDeserializer
     */
    private $xmlDeserializer;

    public function __construct(PersonMergedNotificationHandlerInterface $personMergedNotificationHandler)
    {
        $this->personMergedNotificationHandler = $personMergedNotificationHandler;
        $this->xmlDeserializer = new XmlDeserializer(PersonMergedNotificationDto::class, []);
    }

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

    /**
     * @inheritDoc
     */
    public function handle(?string $messageType, Message $message)
    {
        /** @var PersonMergedNotificationDto $dto */
        $dto = MessageHandlingHelper::getDto($message, PersonMergedNotificationDto::class, $this->xmlDeserializer);
        $operationTimestamp = DateTimeValidatingParser::parse($dto->OperationTimestamp, "OperationTimestamp");
        self::validateDto($dto);

        $notificationData = new PersonMergedNotification($dto->PrimaryPersonFIFAId, $dto->SecondaryPersonFIFAId, $dto->ActorName, $operationTimestamp);
        $this->personMergedNotificationHandler->execute($notificationData);
    }

    /**
     * @param PersonMergedNotificationDto $dto
     * @throws ValidationException
     */
    private static function validateDto(PersonMergedNotificationDto $dto)
    {
        FifaIdValidator::validate($dto->PrimaryPersonFIFAId, "PrimaryPersonFIFAId");
        FifaIdValidator::validate($dto->SecondaryPersonFIFAId, "SecondaryPersonFIFAId");
        ApiModelValidator::cannotBeNullOrWhitespace($dto->ActorName, "ActorName");
    }

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