<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Remote\Entity;

use FiloBlu\Refilo\Helper\PageBuilderConverter;
use Magento\Cms\Api\Data\PageInterface;
use Magento\Store\Model\StoreManagerInterface;
use Sabberworm\CSS\Parsing\SourceException;

class MagentoToRefiloCmsPageAdapter
{
    /**
     * @var PageBuilderConverter
     */
    private $pageBuilderConverter;
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @param PageBuilderConverter $pageBuilderConverter
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        PageBuilderConverter  $pageBuilderConverter,
        StoreManagerInterface $storeManager
    )
    {
        $this->pageBuilderConverter = $pageBuilderConverter;
        $this->storeManager = $storeManager;
    }

    /**
     * @param PageInterface | \Magento\Cms\Model\Page $page
     * @param CmsPage $refiloCmsPage
     * @return CmsPage
     * @throws SourceException
     */
    public function adapt(PageInterface $page, CmsPage $refiloCmsPage): CmsPage
    {
        $storeCode = $page->getStoreCode();
        $id = "page_{$page->getId()}_$storeCode";
        return $refiloCmsPage
            ->setId($id)
            ->addData(
            [
                'metacode' => 'page',
                'store' => $storeCode,
                'content_id' => (int)$page->getId(),
                'url_key' => $page->getIdentifier(),
                'idx' => $page->getIdentifier(),
                'title' => $page->getTitle(),
                'type' => 'page',
                'meta_title' => $page->getMetaTitle(),
                'meta_description' => $page->getMetaDescription(),
                'meta_keywords' => $page->getMetaKeywords(),
                'content_heading' => $page->getContentHeading(),
                'refilo_layout' => $page->getRefiloLayout(),
                'refilo_template' => $page->getRefiloTemplate(),
                'heading_visible' => (bool)$page->getHeadingVisible(),
                'breadcrumbs_visible' => (bool)$page->getBreadcrumbsVisible(),
                'og_data_image' => $page->getOgDataImage(),
                'header_type' => $page->getHeaderType(),
                'css_class' => $page->getCssClass(),
                'css_style' => $page->getCssStyle(),
                'robots' => $page->getRobots(),
                'status' => $page->isActive(),
                'content' => $this->pageBuilderConverter->convert($page->getContent())
            ]
        );
    }
}
