<?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;

/**
 * Class CustomerHubspotSaveAfterProducer
 * @package FiloBlu\Esb\Model\Producer
 */
class CustomerHubspotSaveAfterProducer extends AbstractCustomerHubspotProducer
{

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

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

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

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

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

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

        return $message;
    }

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

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

        $customer_data = $customer->getData();

        $dataToEvaluate->setData('data', $customer_data);
        return $dataToEvaluate;
    }

    /**
     * @param Customer $customer
     * @return mixed
     */
    protected function getDataForFiller( $customer)
    {
        $customer_data = $customer->getData();

        return $this->dataObjectFactory->create(
            [
                'data' => [
                    'data' => $customer_data
                ]
            ]
        );
    }

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

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