<?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\Sales\Api\Data\OrderInterface;

/**
 * Class AbstractOrderProducer
 * @package FiloBlu\Esb\Model\Producer
 */
class OrderSaveAfterProducer extends AbstractOrderProducer
{

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

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

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

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

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

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

        return $message;
    }

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

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

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

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

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

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