<?php

namespace FiloBlu\Refilo\Model\Consumer;

use FiloBlu\Esb\Api\Data\MessageInterface;
use FiloBlu\Esb\Api\Data\MessageInterfaceFactory;
use FiloBlu\Esb\Api\Data\ObjectTypeDescriptorInterface;
use FiloBlu\Esb\Api\Data\StatusInterface;
use FiloBlu\Esb\Api\Data\StatusInterfaceFactory;
use FiloBlu\Esb\Core\Expression\EvaluatorInterfaceFactory;
use FiloBlu\Esb\Core\Extractor\ObjectTypeFromMessage;
use FiloBlu\Esb\Framework\Consumer\AbstractConsumer;
use FiloBlu\Refilo\Model\NewsletterManagement;
use FiloBlu\Refilo\Model\NewsletterManagementFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Phrase;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

/**
 * Class NewsletterConsumer
 * @package FiloBlu\Refilo\Model\Consumer
 */
class NewsletterConsumer extends AbstractConsumer
{

    /**
     * @var NewsletterManagementFactory
     */
    private $newsletterFactory;
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * NewsletterConsumer constructor.
     * @param EvaluatorInterfaceFactory $evaluatorFactory
     * @param ObjectTypeDescriptorInterface $objectTypeDescriptor
     * @param MessageInterfaceFactory $messageFactory
     * @param ObjectTypeFromMessage $objectTypeFromMessage
     * @param StatusInterfaceFactory $statusFactory
     * @param StoreManagerInterface $storeManager
     * @param LoggerInterface $logger
     * @param NewsletterManagementFactory $newsletter
     */
    public function __construct(
        EvaluatorInterfaceFactory $evaluatorFactory,
        ObjectTypeDescriptorInterface $objectTypeDescriptor,
        MessageInterfaceFactory $messageFactory,
        ObjectTypeFromMessage $objectTypeFromMessage,
        StatusInterfaceFactory $statusFactory,
        StoreManagerInterface $storeManager,
        LoggerInterface $logger,
        NewsletterManagementFactory $newsletter
    )
    {
        parent::__construct($evaluatorFactory, $objectTypeDescriptor, $messageFactory, $objectTypeFromMessage, $statusFactory, $logger);
        $this->newsletterFactory = $newsletter;
        $this->storeManager = $storeManager;
    }

    /**
     * @param MessageInterface $message
     * @return MessageInterface
     * @throws LocalizedException
     * @throws NoSuchEntityException
     */
    public function consume(MessageInterface $message): MessageInterface
    {
        if (!$this->isConditionSatisfied($message->getPayload())) {
            $this->getStatus()->setCode(StatusInterface::SKIPPED)->setOutputData('Condition was not satisfied');
            return $this->messageFactory->create();
        }

        /** @var NewsletterManagement $newsletterModel */
        $newsletterModel = $this->newsletterFactory->create();
        $payload = $message->getPayload();

        $isSubscribed = (strtolower($payload->getDataByPath('fields/subscribe_newsletter') ??'') == 'false' ? false : true);
        $newsletterPrivacy = (strtolower($payload->getDataByPath('fields/newsletter_privacy') ??'') == 'false' ? false : true);

        if (!$newsletterPrivacy){
            throw new NoSuchEntityException(new Phrase('Privacy not accepted'));
        }

        if ($isSubscribed) {

            /**
            $result = $newsletterModel->subscribe(
            $payload->getDataByPath('fields/email'),
            $payload->getDataByPath('fields/source'),
            $payload->getDataByPath('fields/firstname'),
            $payload->getDataByPath('fields/lastname'),
            $payload->getDataByPath('fields/dob'),
            $payload->getDataByPath('fields/gender'),
            $payload->getDataByPath('fields/country'),
            $payload->getDataByPath('fields/collections'),
            $payload->getDataByPath('fields/phone'),
            $payload->getDataByPath('fields/language'),
            $payload->getDataByPath('fields/website_name'),
            $payload->getDataByPath('fields/store')
            );**/

            // ->subscribe is deprecated but kept as legacy
            $result = $newsletterModel->subscribeFromPayload($payload);

            if ($result->getData('success') === false) {
                $this->getStatus()->setOutputData($result->toJson())->setCode(StatusInterface::ERROR);
            } else {
                $this->getStatus()->setOutputData($result->toJson())->setCode(StatusInterface::SUCCESS);
            }
            return $this->messageFactory->create();
        }

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

        if ($parameters->getDataByPath('newsletter/allow_unsubscribe')) {
            $newsletterModel->unsubscribe($payload->getDataByPath('fields/email'));
        }

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

        return $this->messageFactory->create();
    }

    public function getName(): string
    {
        return 'Refilo Form Newsletter consumer';
    }

    public function getUniqueName(): string
    {
        return 'FiloBlu_Refilo::form_newsletter_consumer';
    }
}
