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

/**
 * Class InvoiceSaveAfter
 * @package FiloBlu\Esb\Model\Producer
 */
class SubscriberSaveAfterProducer extends AbstractSubscriberProducer
{

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

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

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

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

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

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

        return $message;
    }

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

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

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

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

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

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