<?php


namespace Fifa\ConnectId\Sdk\Notifications;

use Fifa\ConnectId\Sdk\MessageHandlers\MessageHandlerInterface;
use Fifa\ConnectId\Sdk\MessageHandlers\MessageHandlersUtil;
use Fifa\ConnectId\Sdk\Util\Data\Gender;
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 GenderChangedMessageHandler implements MessageHandlerInterface
{
    /**
     * @var GenderChangedNotificationHandlerInterface
     */
    private $genderChangedNotificationHandler;
    /**
     * @var XmlDeserializer
     */
    private $xmlDeserializer;

    public function __construct(GenderChangedNotificationHandlerInterface $genderChangedNotificationHandler)
    {
        $this->genderChangedNotificationHandler = $genderChangedNotificationHandler;
        $this->xmlDeserializer = new XmlDeserializer(GenderChangedNotificationDto::class, []);
    }

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

    /**
     * @inheritDoc
     */
    public function handle(?string $messageType, Message $message)
    {
        /** @var GenderChangedNotificationDto $dto */
        $dto = MessageHandlingHelper::getDto($message, GenderChangedNotificationDto::class, $this->xmlDeserializer);
        $operationTimestamp = MessageHandlingHelper::validateAndParse($dto);
        ApiModelValidator::mustBeNullOrMatchEnumValue($dto->Before, Gender::getGenders(), "Before");
        ApiModelValidator::mustBeNullOrMatchEnumValue($dto->After, Gender::getGenders(), "After");

        $notificationData = new GenderChangedNotification(
            $dto->PersonFIFAId,
            $dto->Before,
            $dto->After,
            $dto->ActorName,
            $operationTimestamp);
        $this->genderChangedNotificationHandler->execute($notificationData);
    }

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