<?php

namespace FiloBlu\Esb\Model\Consumer;

use FiloBlu\Esb\Api\Data\MessageInterface;
use FiloBlu\Esb\Api\Data\StatusInterface;
use FiloBlu\Esb\Core\Exception\NonRecoverableException;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Class SendOrderToEndpointConsumer
 * @package FiloBlu\Esb\Model\Consumer
 */
class SendCustomerToEndpointConsumer extends SendObjectToEndpointConsumer
{

    /**
     * @param MessageInterface $message
     * @return MessageInterface
     * @throws NoSuchEntityException
     * @throws NonRecoverableException
     */
    public function consume(MessageInterface $message): MessageInterface
    {
        $customer = $this->loadObject($message);

        if (!$this->checkConditions($customer, $message))
        {
            $this->getStatus()
                 ->setCode(StatusInterface::SKIPPED)
                 ->setOutputData('Required data missed')
            ;
            return $message;
        }

        $outputMessage = parent::consume($message);

        if ($this->getStatus()
                 ->getCode() !== StatusInterface::SUCCESS)
        {
            return $outputMessage;
        }

        $this->performAction($customer, $message);
        return $outputMessage;
    }

    protected function checkConditions($object, $message)
    {
        // TODO implement message data validation

        return true;
    }

    /**
     * @param $customer
     * @param $message
     * @throws \FiloBlu\Esb\Core\Exception\NonRecoverableException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    protected function performAction($customer, $message)
    {
        $parameters = $this->getConfiguration()
                           ->getParameters()
        ;

        $action = $parameters->getData('on_success_action');

        if ($action === null)
        {
            return;
        }

        $payload = $message->getPayload();
        $payload->setData('object_type', 'customer');
        $payload->setData('object_id', $customer->getId());
        $message->setPayload($payload);
        $object = $this->loadObject($message);
        $argument = $action['parameters'];

        switch ($action['action'])
        {
            case 'change_group_id':
                if ((int)$argument > 0)
                {
                    $object->setData('group_id', $argument);
                }
                break;
            default:
                return;
        }

        $this->saveObject($object);
    }

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'Send Customer to E.P.';
    }

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