<?php

namespace FiloBlu\Esb\Model\Producer;

use FiloBlu\Esb\Api\Data\MessageInterface;
use FiloBlu\Esb\Api\Data\StatusInterface;
use FiloBlu\Esb\Core\Extractor\ObjectTypeFromMessage;
use Magento\Framework\DataObject;
use Magento\Customer\Model\Address\AddressModelInterface as AddressInterface;

/**
 * Class CustomerAddressSaveAfterProducer
 * @package FiloBlu\Esb\Model\Producer
 */
class CustomerAddressSaveAfterProducer extends AbstractCustomerAddressProducer
{

    /**
     * @inheritDoc
     */
    public function produce(AddressInterface $address = null): MessageInterface
    {
        /** @var MessageInterface $message */
        $message = $this->getMessageFactory()->create();

        if ($address === null || !$this->isConditionSatisfied($this->prepareDataForEvaluation($address))) {
            $this->getStatus()
                ->setCode(StatusInterface::SKIPPED)
                ->setOutputData($address === null ? 'Address was null' : 'Condition was not satisfied');
            return $message;
        }

        $parameters = $this->getConfiguration()->getParameters();

        if ($address !== null && $parameters->hasData(self::PAYLOAD_KEY)) {
            $template = $parameters->getData(self::PAYLOAD_KEY);
            $this->messageFiller->fill($message, $this->getDataForFiller($address), $template);
        }

        $message->getPayload()->addData([
            ObjectTypeFromMessage::OBJECT_TYPE_PATH => $this->getObjectTypeDescriptor()->getTypeCode(),
            ObjectTypeFromMessage::OBJECT_ID_PATH => $address->getEntityId()
        ]);

        $this->getStatus()->setCode(StatusInterface::SUCCESS);

        return $message;
    }

    /**
     * @param AddressInterface $address
     * @return DataObject
     */
    protected function prepareDataForEvaluation(AddressInterface $address = null): DataObject
    {
        /** @var DataObject $dataToEvaluate */
        $dataToEvaluate = $this->dataObjectFactory->create();

        if ($address === null) {
            return $dataToEvaluate;
        }

        $dataToEvaluate->setData('data', $address);
        $dataToEvaluate->setData('origdata', $address->getOrigData() ?: $this->dataObjectFactory->create());
        return $dataToEvaluate;
    }

    /**
     * @param AddressInterface $creditmemo
     * @return mixed
     */
    protected function getDataForFiller(AddressInterface $address)
    {
        return $this->dataObjectFactory->create(
            [
                'data' => [
                    'data' => $address,
                    'origdata' => $address->getOrigData() ?: $this->dataObjectFactory->create()
                ]
            ]
        );
    }

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'Customer Address Save After Producer';
    }

    /**
     * @inheritDoc
     */
    public function getUniqueName(): string
    {
        return 'FiloBlu_Esb::customer_address_save_after';
    }
}
