<?php

namespace FiloBlu\Refilo\Model\Exporter;

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

/**
 * Class CmsPage
 * @package FiloBlu\Refilo\Model\Exporter
 */
class CmsPage extends AbstractCmsExporter
{
    /** @var PageCollectionFactory */
    protected $pageCollectionFactory;

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

    /**
     * Menu constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param Mongo $mongo
     * @param StoreManagerInterface $storeManager
     * @param Configuration $coreConfiguration
     * @param PageCollectionFactory $pageCollectionFactory
     * @param \FiloBlu\Refilo\Helper\PageBuilderConverter $pageBuilderConverter
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        Mongo $mongo,
        StoreManagerInterface $storeManager,
        Configuration $coreConfiguration,
        PageCollectionFactory $pageCollectionFactory,
        PageBuilderConverter $pageBuilderConverter
    ) {
        parent::__construct($mongo, $coreConfiguration, $scopeConfig, $storeManager);
        $this->pageCollectionFactory = $pageCollectionFactory;
        $this->pageBuilderConverter = $pageBuilderConverter;
    }

    /**
     *
     * @throws \Sabberworm\CSS\Parsing\SourceException|\Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute(OutputInterface $output = null)
    {
        foreach ($this->getStoreManager()->getStores() as $store) {
            $projectId = $this->getDatabaseByWebsiteCode($store->getWebsite()->getCode());

            if (!$projectId) {
                continue;
            }

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

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

                $bulk[] = [
                    '_id'                 => 'page_' . $item->getId() . '_' . $store->getData('code'),
                    'metacode'            => 'page',
                    'store'               => $store->getData('code'),
                    'content_id'          => (int)$item->getId(),
                    'url_key'             => $identifier,
                    'idx'                 => $identifier,
                    'title'               => $item->getTitle(),
                    'type'                => 'page',
                    'meta_title'          => $item->getMetaTitle(),
                    'meta_description'    => $item->getMetaDescription(),
                    'meta_keywords'       => $item->getMetaKeywords(),
                    'content_heading'     => $item->getContentHeading(),
                    'refilo_layout'       => $item->getRefiloLayout(),
                    'refilo_template'     => $item->getRefiloTemplate(),
                    'heading_visible'     => (bool)$item->getHeadingVisible(),
                    'breadcrumbs_visible' => (bool)$item->getBreadcrumbsVisible(),
                    'og_data_image'       => $item->getOgDataImage(),
                    'header_type'         => $item->getHeaderType(),
                    'css_class'           => $item->getCssClass(),
                    'css_style'           => $item->getCssStyle(),
                    'robots'              => $item->getRobots(),
                    'status'              => $item->isActive(),
                    'content'             => $this->pageBuilderConverter->convert($item->getContent()),
                    'customer_group'      => $item->getCustomerGroup() !== null ? array_map(
                        '\intval',
                        explode(',', $item->getCustomerGroup())
                    ) : null
                ];
            }

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

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

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

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

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

        $identifier = $item->getIdentifier();

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

        return null;
    }
}
