<?php

namespace FiloBlu\Esb\Controller\Adminhtml\Queue;

use Exception;
use FiloBlu\Esb\Api\Data\QueueItemInterface;
use FiloBlu\Esb\Api\Data\StatusInterface;
use FiloBlu\Esb\Api\QueueItemRepositoryInterface;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultInterface;
use Throwable;

/**
 * Class Hold
 * @package FiloBlu\Esb\Controller\Adminhtml\Queue
 */
class Enqueue extends Action
{
    /**
     * @var QueueItemRepositoryInterface
     */
    private $queueItemRepository;

    /**
     * Constructor
     *
     * @param Context $context
     * @param QueueItemRepositoryInterface $queueItemRepository
     */
    public function __construct(
        Context $context,
        QueueItemRepositoryInterface $queueItemRepository
    ) {
        parent::__construct($context);
        $this->queueItemRepository = $queueItemRepository;
    }

    /**
     * Execute view action
     *
     * @return ResultInterface
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id', null);

        if ($id) {
            try {
                /** @var QueueItemInterface $queueItem */
                $queueItem = $this->queueItemRepository->getById($id);

                    $queueItem->getStatus()->setCode(StatusInterface::PENDING);
                    $this->queueItemRepository->save($queueItem);
                    $this->messageManager->addSuccessMessage(__('Queue item is pendig'));
            } catch (Exception $exception) {
                $this->messageManager->addExceptionMessage($exception);
            } catch (Throwable $throwable) {
                $this->messageManager->addExceptionMessage($throwable);
            }

            return $this->resultRedirectFactory->create()->setPath('*/*/view', ['id' => $id]);
        }

        return $this->resultRedirectFactory->create()->setPath('*/*/index');
    }
}
