<?php
declare(strict_types=1);

namespace FoundationCommerce\ThemeViewModels\ViewModels;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\GetBlockByIdentifierInterface;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Store\Model\StoreManagerInterface;

class CmsBlockContentProvider implements ArgumentInterface
{
    /**
     * @var BlockRepositoryInterface
     */
    protected $blockRepository;
    /**
     * @var GetBlockByIdentifierInterface
     */
    protected $getBlockByIdentifier;
    /**
     * @var FilterProvider
     */
    protected $filterProvider;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    public function __construct(
        BlockRepositoryInterface $blockRepository,
        GetBlockByIdentifierInterface $getBlockByIdentifier,
        StoreManagerInterface $storeManager,
        FilterProvider $filterProvider
    ) {
        $this->blockRepository = $blockRepository;
        $this->getBlockByIdentifier = $getBlockByIdentifier;
        $this->filterProvider = $filterProvider;
        $this->storeManager = $storeManager;
    }

    public function getBlockTitle(string $identifier): string
    {
        $storeId = $this->getStoreId();
        $block = $this->getBlockByIdentifier->execute($identifier, $storeId);

        if (!$block->isActive()) {
            return '';
        }

        return $block->getTitle();
    }

    public function getBlockHtml(string $identifier): string
    {
        $storeId = $this->getStoreId();

        try {
            $block = $this->getBlockByIdentifier->execute($identifier, $storeId);
        } catch (NoSuchEntityException $e) {
            return '';
        }

        if (!$block->isActive()) {
            return '';
        }


        return $this->filterProvider->getBlockFilter()->setStoreId($storeId)->filter($block->getContent());
    }

    protected function getStoreId(): int
    {
        return (int)$this->storeManager->getStore()->getId();
    }
}
