<?php
namespace Autogedal\CmsRestDisable\Model;

use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Api\Data\BlockSearchResultsInterface;
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Webapi\Rest\Request;

class BlockRepository implements BlockRepositoryInterface
{
    /**
     * @var BlockRepositoryInterface
     */
    private $blockRepository;

    /**
     * @var Request
     */
    private $request;

    /**
     * @param BlockRepositoryInterface $blockRepository
     * @param Request $request
     */
    public function __construct(
        \Magento\Cms\Model\BlockRepository $blockRepository,
        Request $request
    ) {
        $this->blockRepository = $blockRepository;
        $this->request = $request;
    }

    /**
     * @inheritdoc
     */
    public function save(BlockInterface $block)
    {
        if ($this->isApiRequest()) {
            throw new LocalizedException(__('The CMS block save operation has been disabled via API.'));
        }
        return $this->blockRepository->save($block);
    }

    /**
     * @inheritdoc
     */
    public function getById($blockId)
    {
        return $this->blockRepository->getById($blockId);
    }

    /**
     * @inheritdoc
     */
    public function getList(SearchCriteriaInterface $searchCriteria)
    {
        return $this->blockRepository->getList($searchCriteria);
    }

    /**
     * @inheritdoc
     */
    public function delete(BlockInterface $block)
    {
        if ($this->isApiRequest()) {
            throw new LocalizedException(__('The CMS block delete operation has been disabled via API.'));
        }
        return $this->blockRepository->delete($block);
    }

    /**
     * @inheritdoc
     */
    public function deleteById($blockId)
    {
        if ($this->isApiRequest()) {
            throw new LocalizedException(__('The CMS block delete operation has been disabled via API.'));
        }
        return $this->blockRepository->deleteById($blockId);
    }

    /**
     * Check if the request is coming from the API
     *
     * @return bool
     */
    private function isApiRequest()
    {
        return $this->request->getRequestUri() && strpos($this->request->getRequestUri(), '/rest/') === 0;
    }
}
