<?php

namespace FiloBlu\Refilo\Model\Exporter;

use Exception;
use FiloBlu\Core\Model\Configuration;
use FiloBlu\Refilo\Helper\PageBuilderConverter;
use FiloBlu\Refilo\Model\Adapter\Mongo;
use Magento\Cms\Model\ResourceModel\Block\CollectionFactory as BlockCollectionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class CmsBlock
 * @package FiloBlu\Refilo\Model\Exporter
 */
class CmsBlock extends AbstractCmsExporter
{
    /**
     * @var BlockCollectionFactory
     */
    protected $blockCollectionFactory;

    /**
     * @var PageBuilderConverter
     */
    private $pageBuilderConverter;


    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \FiloBlu\Refilo\Model\Adapter\Mongo $mongo
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \FiloBlu\Core\Model\Configuration $coreConfiguration
     * @param \Magento\Cms\Model\ResourceModel\Block\CollectionFactory $blockCollectionFactory
     * @param \FiloBlu\Refilo\Helper\PageBuilderConverter $pageBuilderConverter
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        Mongo $mongo,
        StoreManagerInterface $storeManager,
        Configuration $coreConfiguration,
        BlockCollectionFactory $blockCollectionFactory,
        PageBuilderConverter $pageBuilderConverter
    ) {
        parent::__construct($mongo, $coreConfiguration, $scopeConfig, $storeManager);
        $this->blockCollectionFactory = $blockCollectionFactory;
        $this->pageBuilderConverter = $pageBuilderConverter;
    }

    /**
     * @return string
     */
    public function getMetaCode(): string
    {
        return 'block';
    }

    /**
     * @param \Symfony\Component\Console\Output\OutputInterface|null $output
     * @return void
     * @throws \Sabberworm\CSS\Parsing\SourceException
     */
    public function execute(OutputInterface $output = null)
    {
        /** @var Store $store */
        foreach ($this->getStoreManager()->getStores() as $store) {
            $projectId = $this->getDatabaseByWebsiteCode($store->getWebsite()->getCode());

            if (!$projectId) {
                continue;
            }

            $blocks = $this->blockCollectionFactory->create()
                ->addStoreFilter($store)
                ->addFilter('is_active', 1);

            $bulk = [];
            foreach ($blocks as $item) {
                $identifier = $this->getIdentifier($item);

                $bulk[] = [
                    '_id'                      => 'block_' . $item->getId() . '_' . $store->getData('code'),
                    'metacode'                 => 'block',
                    'store'                    => $store->getData('code'),
                    'content_id'               => (int)$item->getId(),
                    'url_key'                  => $identifier,
                    'idx'                      => $identifier,
                    'title'                    => $item->getTitle(),
                    'type'                     => 'static_block',
                    'status'                   => $item->isActive(),
                    'content'                  => $this->pageBuilderConverter->convert($item->getContent()),
                    'display_entity'           => $item->getDisplayOn(),
                    'display_selection_type'   => $item->getSelectionType(),
                    'display_selection_target' => $this->parseTargetSelection($item->getSelectionTarget()),
                    'display_container'        => $item->getRefiloLayoutContainer(),
                    'display_sort_order'       => (int)$item->getRefiloLayoutOrder(),
                    'listing_display_page'     => (int)$item->getListingDisplayPage(),
                    'listing_display_position' => (int)$item->getListingDisplayPosition(),
                    'listing_columns_spacing'  => (int)$item->getListingColumnsSpacing(),
                    'listing_row_spacing'      => (int)$item->getListingRowSpacing(),
                    'customer_group'           => $item->getCustomerGroup() !== null ? array_map(
                        '\intval',
                        explode(',', $item->getCustomerGroup())
                    ) : null
                ];
            }

            try {
                $this->getConnection()->update(
                    '_id',
                    $bulk,
                    'contents_' . $store->getCode(),
                    true,
                    $projectId
                );
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
    }

    /**
     * @param $value
     * @return false|string[]
     */
    public function parseTargetSelection($value)
    {
        $strippedValue = preg_replace('/\s/', '', $value ?? '');
        return explode(',', $strippedValue);
    }

    /**
     * @return string
     */
    public function getCollectionPrefix(): string
    {
        return 'contents_';
    }

    /**
     * @param $item
     * @return mixed
     */
    public function getIdentifier($item)
    {
        $identifier = $item->getRefiloIdentifier();

        if ($identifier !== null && $identifier !== '') {
            return $identifier;
        }

        $identifier = $item->getIdentifier();

        if ($identifier !== null && $identifier !== '') {
            return $identifier;
        }

        return null;
    }
}
