<?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\Quote\Model\Quote;

/**
 * Class AbstractQuoteProducer
 * @package FiloBlu\Esb\Model\Producer
 */
class QuoteSaveAfterProducer extends AbstractQuoteProducer
{

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

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

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

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

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

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

        return $message;
    }

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

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

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

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

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

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