<?php
declare(strict_types=1);

namespace FiloBlu\Esb\Model\Producer;

use FiloBlu\Esb\Api\Data\MessageInterface;
use FiloBlu\Esb\Api\Data\StatusInterface;
use FiloBlu\Esb\Core\Extractor\ObjectTypeFromMessage;
use FiloBlu\Esb\Framework\Producer\AbstractProducer;
use Magento\Framework\DataObject;
use Magento\Sales\Model\Order\Shipment;

/**
 * Class ShipmentProducer
 * @package FiloBlu\Esb\Model\Producer
 */
class ShipmentProducer extends AbstractProducer
{

    /**
     * @param Shipment|null $shipment
     * @return MessageInterface
     */
    public function produce( Shipment $shipment = null): MessageInterface
    {
        /** @var MessageInterface $message */
        $message = $this->getMessageFactory()->create();

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

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

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

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

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

        return $message;
    }

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

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

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

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

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'Shipment Producer';
    }

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