<?php

namespace Fifa\ConnectId\Sdk\Util\MessageSerializers;

use Fifa\ConnectId\Sdk\Model\Transfer\DomesticTransferDeclaration;
use Fifa\ConnectId\Sdk\Util\PersonLocalXmlSerializer\PersonLocalXmlSerializer;
use Fifa\ConnectId\Sdk\Util\PersonLocalXmlSerializer\PersonLocalXmlSerializerInterface;
use Fifa\ConnectId\Sdk\Util\Serialization\Configurations\CommonXmlSerializerConfiguration;
use Fifa\ConnectId\Sdk\Util\Serialization\Configurations\DomesticTransferDeclarationXmlSerializerConfiguration;
use Fifa\ConnectId\Sdk\Util\Serialization\ValidatingXmlSerializerBase;
use Fifa\ConnectId\Sdk\Util\XmlDeserializer\XmlDeserializer;
use XML_Serializer;

class DomesticTransferDeclarationXmlSerializer extends ValidatingXmlSerializerBase
{
    /**
     * @var PersonLocalXmlSerializerInterface
     */
    private $personLocalSerializer;

    public function __construct()
    {
        $this->personLocalSerializer = new PersonLocalXmlSerializer();

        $xmlDeserializer = new XmlDeserializer(DomesticTransferDeclaration::class,
            DomesticTransferDeclarationXmlSerializerConfiguration::getMappings(),
            CommonXmlSerializerConfiguration::getCustomConstructors()
        );

        $xmlSerializer = new XML_Serializer();
        $xmlSerializer->setOptions(CommonXmlSerializerConfiguration::buildOptions('DomesticTransferDeclaration',
            [
                XML_SERIALIZER_OPTION_SCALAR_AS_ATTRIBUTES => DomesticTransferDeclarationXmlSerializerConfiguration::getScalarAsAttributes(),
                XML_SERIALIZER_OPTION_TAGMAP => DomesticTransferDeclarationXmlSerializerConfiguration::getTagmap()
            ]
        ));

        parent::__construct($xmlSerializer, $xmlDeserializer);
    }

    /**
     * @inheritDoc
     * @param DomesticTransferDeclaration $declaration
     */
    protected function nullifyUnsetArrays($declaration)
    {
        if ($declaration->PersonLocal !== null) {
            $this->personLocalSerializer->nullifyUnsetArrays($declaration->PersonLocal);
        }
        if (is_array($declaration->FixedTransferFee) && empty($declaration->FixedTransferFee)) {
            $declaration->FixedTransferFee = null;
        }
        if (is_array($declaration->ConditionalTransferFee) && empty($declaration->ConditionalTransferFee)) {
            $declaration->ConditionalTransferFee = null;
        }
        if (is_array($declaration->ReleaseBuyoutFee) && empty($declaration->ReleaseBuyoutFee)) {
            $declaration->ReleaseBuyoutFee = null;
        }
    }
}