<?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 Index
 * @package FiloBlu\Esb\Controller\Adminhtml\Queue
 */
class Resume 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);

                if ($queueItem->getStatus()->getCode() === StatusInterface::ON_HOLD) {
                    $queueItem->getStatus()->setCode(StatusInterface::PENDING);
                    $this->queueItemRepository->save($queueItem);
                    $this->messageManager->addSuccessMessage(__('Queue item is set in pending'));
                } else {
                    $this->messageManager->addErrorMessage(__('Only item on hold status can be set on pending'));
                }
            } 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');
    }
}
